Questions:
Given non-negative numbers NUM1 and num2 represented as String, return the sum of NUM1 and num2.
Note:
1. The length of both NUM1 and num2 is < 5100.
2, Both NUM1 and num2 contains only digits 0-9.
3, Both NUM1 and num2 does not contain any leading zero.
4. You must don't use any built-in BigInteger library or convert the inputs to integer directly. Effect:
Gives two non-negative NUM1 and num2 in string form, returning the sum of NUM1 and num2.
Attention:
1, NUM1 and num2 are less than 5100 in length.
2, NUM1 and num2 contain only the number 0-9.
3, NUM1 and num2 are not included in the first 0.
4. You cannot use any of the built-in large number libraries or convert the input directly into an integer type. Ideas:
The title is not allowed to be converted directly into integral type to calculate, that is, we want to add the number of a one to achieve an addition. From the end of the two strings to add, pay attention to determine whether to carry, a bit to two strings are traversed so far, in order to speed here to use StringBuilder, if directly with + to do character stitching is too slow, pay attention to each of us on each number of overtime or the integer type to calculate, This is still allowed, otherwise it is too troublesome, the code is easier to read. Code (JAVA):
public class Solution {public String addstrings (string num1, String num2) {if (NUM1
. Length () = = 0) return num2;
else if (num2.length () = = 0) return NUM1;
Boolean hasup = false;//whether rounding int i = Num1.length ()-1;
Int J = num2.length ()-1;
StringBuilder sb = new StringBuilder ();
while (I >=0 | | J >= 0) {int n1 = i >= 0? num1.charat (i)-' 0 ': 0; int n2 = J >= 0?
Num2.charat (j)-' 0 ': 0;
int sum = n1 + N2 + (hasup? 1:0);
if (sum >=) {sb.insert (0, integer.tostring (sum-10));
Hasup = true;
} else {Sb.insert (0, integer.tostring (sum));
Hasup = false;
} i--;
j--;
} if (hasup) sb.insert (0, "1");
return sb.tostring (); }
}
Collection: Https://github.com/Cloudox/LeetCode-Record
All rights reserved: Http://blog.csdn.net/cloudox_