题目
中文
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
英文
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
解题思路
- 转化为整型数组,按位相加,设置进位标志符
class Solution {
public static String delZero(int[] num){ //将数组返回成一个首字符不为0的字符串
int i;
String str = new String();
for(i = 0;i<num.length;i++){
if(num[i] != 0)
break;
}
for(;i<num.length;i++){
str += (char)(num[i] + '0');
}
return str;
}
public static int max(int[] a, int[] b){
return a.length>b.length?a.length:b.length;
}
public static int min(int[] a,int[] b){
return a.length<b.length?a.length:b.length;
}
public static int[] tointArray(String num){ //将string转化为int数组
char[] n = num.toCharArray();
int len = n.length;
int[] res = new int[len];
for(int i = 0;i < len;i++)
res[i] = n[i] - 48;
return res;
}
public String addStrings(String num1, String num2) {
if(num2.equals("0") && num1.equals("0"))
return "0";
int[] n1 = tointArray(num1);
int[] n2 = tointArray(num2);
int len = max(n1,n2);
int[] res = new int[len + 1]; //两数相加最多多一位
int flag = 0; //进位标志
int i = n1.length - 1,j = n2.length - 1, k = res.length - 1;
while(i >= 0 && j >= 0 && k >= 0){
res[k] = (flag + n1[i] + n2[j]) % 10;
flag = (flag + n1[i] + n2[j]) / 10;
i--;j--;k--;
}
if(i >= 0){
for(;i >= 0 && k >= 0;i--,k--){
res[k] = (flag + n1[i]) % 10;
flag = (flag + n1[i]) / 10;
}
}
if(j >= 0){
for(;j >= 0 && k >= 0;j--,k--){
res[k] = (flag + n2[j]) % 10;
flag = (flag + n2[j]) / 10;
}
}
res[0] += flag; //首位进位处理
String ans = delZero(res);
return ans;
}
}
- 先对齐后操作会节省很多时间和不必要的操作