Given non-negative integers num1
num2
and represented as String, return the sum of num1
num2
.
Note:
- The length of both and is
num1
num2
< 5100.
- Both
num1
and num2
contains only digits 0-9
.
- Both
num1
and num2
does not contain any leading zero.
- You must no built-in BigInteger library or convert the inputs to integer directly.
This problem can not use long will be out of bounds, so can only use string directly to append. The essence is to set a variable to store the carry.
First wrote a Boolean flag to store the carry, the result code logic is very troublesome ... Take into account that the sum of two numbers equals 9, plus 1 of the carry is equal to 10, also take into account the addition of two numbers, and longer than any one number of the length of the time, the highest bit is also added 1.
This is the code I began to write, I can not see anymore ...
Public classSolution { Publicstring AddStrings (String num1, String num2) {if(NUM1 = =NULL|| Num2 = =NULL) { return NULL; } intsum = 0; StringBuilder Str=NewStringBuilder (); for(inti = Num1.length ()-1, J = num2.length ()-1; I >= 0 | | J >= 0; I--, j--) { intx = i < 0? 0:num1.charat (i)-' 0 '; inty = J < 0? 0:num2.charat (j)-' 0 '; Sum= x +y; Sum= Sum% 10; if(flag) {if(sum + 1 >= 10) {flag=true; Str.append (Sum+ 1)% 10); } Else{str.append (sum+ 1); Flag=false; } } Else{str.append (sum); } if(x + y >= 10) {flag=true; } } if(flag) {Str.append (1); } returnstr.reverse (). toString (); }}
But in fact there is a more concise way to use an int type to represent the highest bit, and when it is 1, continue to loop append.
Public classSolution { Publicstring AddStrings (String num1, String num2) {if(NUM1 = =NULL|| Num2 = =NULL) { return NULL; } intCarry = 0; StringBuilder Str=NewStringBuilder (); for(inti = Num1.length ()-1, J = num2.length ()-1; I >= 0 | | J >= 0 | | carry = = 1; I--, j--) { intx = i < 0? 0:num1.charat (i)-' 0 '; inty = J < 0? 0:num2.charat (j)-' 0 '; Str.append ((x+ y + carry)% 10); Carry= (x + y + carry)/10; } returnstr.reverse (). toString (); }}
The logic is much clearer ... = =
ADD Strings Leetcode