study/java/src/com/thinker/bishi/offer/LargeNumPlus.java

37 lines
1.0 KiB
Java

package com.thinker.bishi.offer;
/**
* @author lzh
* @apiNote 大数相加
*/
public class LargeNumPlus {
private static String plus(String s1,String s2){
if(s1 == null || s2 == null) return "0";
StringBuilder result = new StringBuilder();
int carry = 0;
int tmp ;
//plus
for(int i=s1.length()-1,j=s2.length()-1;i>=0 || j>=0;i--,j--){
tmp = 0;
if(i>=0) tmp += s1.charAt(i)-48;
if(j>=0) tmp += s2.charAt(j)-48;
tmp += carry;
carry = tmp/10;
result.append(tmp%10);
}
//旋转
for(int i=0;i<result.length()-1-i;i++){
char tmpChar = result.charAt(i);
result.setCharAt(i,result.charAt(result.length()-1-i));
result.setCharAt(result.length()-1-i,tmpChar);
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "1232";
String s2 = "128";
System.out.println(plus(s1,s2));
}
}