一、问题描述:
Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
二、解决思路:
不能转化为integer,就用char数组,因为char之间直接相加返回的是ascii码。 两个char相加再减去48*2 就得到十进制的结果。(0-9的ascii是48-57)
剩下的就是实现基本的十进制加法啦。要考虑的因素比较多~ 一定要细心
三、代码:
public class Solution {
public String addStrings(String num1, String num2) {
String res = "";
char[] c1 = num1.toCharArray();
char[] c2 = num2.toCharArray();
int temp = 0;
int re = 0;
for (int i = c1.length - 1, j = c2.length - 1; i > -1 && j > -1; i--, j--) {
char cn1 = c1[i];
char cn2 = c2[j];
re = cn1 + cn2 + temp - 48 * 2;
if (re > 9) {
temp = re / 10;
re = re % 10;
} else {
temp = 0;
}
res = re + res;;
}
if (c1.length == c2.length && temp > 0) {
res = temp + res;
return res;
}
if (c1.length - c2.length > 1) {
re = c1[c1.length - c2.length - 1] + temp - 48;
if (re > 9) {
temp = re / 10;
re = re % 10;
} else {
temp = 0;
}
res = re + res;
for (int i = c1.length - c2.length - 2; i > -1; i--) {
re = c1[i] + temp - 48;
if (re > 9) {
temp = re / 10;
re = re % 10;
} else {
temp = 0;
}
res = re + res;
}
if (temp > 0) {
res = temp + res;
}
}
if (c1.length - c2.length == 1) {
re = c1[c1.length - c2.length - 1] + temp - 48;
res = re + res;
}
if (c2.length - c1.length > 1) {
re = c2[c2.length - c1.length - 1] + temp - 48;
if (re > 9) {
temp = re / 10;
re = re % 10;
} else {
temp = 0;
}
res = re + res;
for (int i = c2.length - c1.length - 2; i > -1; i--) {
re = c2[i] + temp - 48;
if (re > 9) {
temp = re / 10;
re = re % 10;
} else {
temp = 0;
}
res = re + res;
}
if (temp > 0) {
res = temp + res;
}
}
if (c2.length - c1.length == 1) {
re = c2[c2.length - c1.length - 1] + temp - 48;
res = re + res;
}
return res;
}
}