415. Add Strings
Given two non-negative integers 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.
字符串表示十进制数,求相加后的结果
C++(19ms):
1 class Solution { 2 public: 3 string addStrings(string num1, string num2) { 4 int i = num1.length() - 1 ; 5 int j = num2.length() - 1 ; 6 int c = 0 ; 7 string res = "" ; 8 while(i >= 0 || j >= 0 || c == 1){ 9 if (i >= 0) 10 c += num1[i--] - '0' ; 11 if (j >= 0) 12 c += num2[j--] - '0' ; 13 res = to_string(c%10) + res ; 14 c/=10 ; 15 } 16 return res ; 17 } 18 };
java(25ms):
1 class Solution { 2 public String addStrings(String num1, String num2) { 3 StringBuilder sb = new StringBuilder() ; 4 int i = num1.length() - 1 ; 5 int j = num2.length() - 1 ; 6 int c = 0 ; 7 while(i >= 0 || j >= 0 || c == 1){ 8 if (i >= 0) 9 c += num1.charAt(i--) - '0'; 10 if (j >= 0) 11 c += num2.charAt(j--) - '0'; 12 sb.append(c%10) ; 13 c/=10 ; 14 } 15 return sb.reverse().toString() ; 16 17 } 18 }