题解 | #大数加法#
大数加法
http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
思路很简单:
例如 1 + 9999999,我们需要从最后加呗,先判断是否进位,在判断当前位置。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 计算两个数之和
* @param s string字符串 表示第一个整数
* @param t string字符串 表示第二个整数
* @return string字符串
*/
public String solve (String s, String t) {
// write code here
int m = s.length();
int n = t.length();
int len = m > n ? m : n;
int[] temp = new int[len + 1];
int index = len;
int left = m-1;
int right = n-1;
while(left >=0 && right>=0){
int temps = temp[index]+ (s.charAt(left--) - '0') + (t.charAt(right--) - '0');
temp[index-1] = temps/10;
temp[index--] = temps%10;
}
while(left >=0){
int temps = temp[index]+ (s.charAt(left--) - '0');
temp[index-1] = temps/10;
temp[index--] = temps%10;
}
while(right >=0){
int temps = temp[index]+ (t.charAt(right--) - '0');
temp[index-1] = temps/10;
temp[index--] = temps%10;
}
StringBuffer sb = new StringBuffer();
index = 0;
while(index<=len && temp[index] == 0){
index++;
}
for(int i = index;i<=len;i++){
sb.append(temp[i]);
}
return sb.toString().equals("") ? "0" : sb.toString();
}
}
查看5道真题和解析
