题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
思路:从一位牛油那里得到的启发,有理有据。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String str1=in.next();
String str2=in.next();
int carry=0;//进位
StringBuilder sb=new StringBuilder();
int i=str1.length()-1;
int j=str2.length()-1;
while(i>=0 || j>=0 || carry!=0){
int x=i<0?0:(str1.charAt(i--)-'0');
int y=j<0?0:(str2.charAt(j--)-'0');
sb.append((x+y+carry)%10);
carry=(x+y+carry)/10;//更新进位
}
System.out.println(sb.reverse());
}
}