NC1题解 | #大数加法#
大数加法
http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
此题目关键
- 1、字符串判空操作
- 2、字符串长度不一致,补全(取最长)还是截取(取最小)再补
- 3、要用StringBuilder代替String做拼接,节省运行时间
import java.util.*;
public class Solution {
public static String solve (String s, String t) {
if(s==null || s.length()==0) {
return t;
}
if(t==null || t.length()==0) {
return s;
}
// write code here
int maxLen = s.length() > t.length() ? s.length() : t.length();
int cin = 0;
int a,b,res;
String ss = "";
char[] ch1 = s.toCharArray();
char[] ch2 = t.toCharArray();
int[] ch = new int[maxLen+1];
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= maxLen; i++){
if(i<=s.length()) {
a = ch1[s.length()-i]-'0';
}else{
a = 0;
}
if(i<=t.length()) {
b = ch2[t.length()-i]-'0';
}else{
b = 0;
}
res = a + b + cin;
if(res>=10){
res = res -10;
cin = 1;
}else{
cin = 0;
}
ch[ch.length-i]=res;
}
if(cin>0){
sb.append(cin);
}
for(int i = 1; i < ch.length; i++){
sb.append(ch[i]);
}
return sb.toString();
}
}

