Given two non-negative numbers 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
Solution:
驚了,將兩個字符串轉換為 long 再相加,再將 result 轉換為 String,居然不對?代碼留在這里先:
/*
* This code is wrong.
*/
public class Solution
{
public String addStrings(String num1, String num2)
{
long num1Int = 0, num2Int = 0;
for (int i = num1.length() - 1; i >= 0; i--)
{
num1Int += (int)(num1.charAt(i) - '0') * Math.pow(10, num1.length() - i - 1);
}
for (int i = num2.length() - 1; i >= 0; i--)
{
num2Int += (int)(num2.charAt(i) - '0') * Math.pow(10, num2.length() - i - 1);
}
long result = num1Int + num2Int;
return String.valueOf(result);
}
}
Input:
"9333852702227987"
"85731737104263"
Output:
"9419584439332251"
Expect:
"9419584439332250"
最高位為9就不對了……溢出?還多1……why?
看了 Discussion 發(fā)現(xiàn)都在模擬豎式加法…………先這么寫吧……還從來沒有模擬過豎式加法就當練習了
public class Solution
{
public String addStrings(String num1, String num2)
{
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;
String result = new String();
while(i >= 0 || j >= 0 || carry >0)
{
int sum = 0;
if(i >= 0)
{
sum += num1.charAt(i) - '0';
}
if(j >= 0)
{
sum += num2.charAt(j) -'0';
}
sum += carry;
carry = (int)sum / 10;
sum = sum % 10;
result = String.valueOf(sum) + result;
i--;
j--;
}
return result;
}
}