题解 | #大数加法#
大数加法
http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
import java.util.*;
public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ public String solve (String s, String t) {
int slength = s.length();
int tlength = t.length();
int sIndex = slength -1;
int tIndex = tlength -1 ;
int charLength = slength > tlength ? s.length()+1 : tlength+1;
int[] chars = new int[charLength];
boolean needMove = false; // 是否需要进位
while (sIndex >= 0 && tIndex >= 0) {
int data;
if (needMove){
// char '0' = 48
data = (int) s.charAt(sIndex) + (int) t.charAt(tIndex) + 1 - 96;
} else {
data = (int) s.charAt(sIndex) + (int) t.charAt(tIndex) - 96;
}
if (data < 10) {
needMove = false;
chars[--charLength] = data;
} else {
needMove = true;
data -= 10;
chars[--charLength] = data;
}
sIndex--;
tIndex--;
}
while (sIndex >= 0 ){
int data;
if (needMove) {
data = (int) s.charAt(sIndex) + 1 - 48;
} else {
data = (int) s.charAt(sIndex) - 48;
}
if (data < 10) {
needMove = false;
chars[--charLength] = data;
} else {
needMove = true;
data -= 10;
chars[--charLength] = data;
}
sIndex--;
}
while (tIndex >= 0 ){
int data;
if (needMove) {
data = (int) t.charAt(tIndex) + 1 - 48;
} else {
data = (int) t.charAt(tIndex) - 48;
}
if (data < 10) {
needMove = false;
chars[--charLength] = data;
} else {
needMove = true;
data -= 10;
chars[--charLength] = data;
}
tIndex--;
}
// 还有一个判断
if (needMove) {
chars[0] = 1;
}
StringBuilder sb = new StringBuilder();
// 第一个是0的去掉
boolean flag = true;
for (int aChar : chars) {
if (aChar != 0){
flag = false;
}
if (!flag){
sb.append(aChar);
}
}
if (sb.length() == 0 ) return "0";
return sb.toString();
}
}