[LeetCode] 415. Add Strings 字符串相加
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.
两个只含有数字的字符串相加。
解法: 对于每个字符转成对应的整数,然后相加,结果在写入res。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Solution { public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0 ; for ( int i = num1.length() - 1 , j = num2.length() - 1 ; i >= 0 || j >= 0 || carry == 1 ; i--, j--){ int x = i < 0 ? 0 : num1.charAt(i) - '0' ; int y = j < 0 ? 0 : num2.charAt(j) - '0' ; sb.append((x + y + carry) % 10 ); carry = (x + y + carry) / 10 ; } return sb.reverse().toString(); } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Solution( object ): def addStrings( self , num1, num2): """ :type num1: str :type num2: str :rtype: str """ result = [] i, j, carry = len (num1) - 1 , len (num2) - 1 , 0 while i > = 0 or j > = 0 or carry: if i > = 0 : carry + = ord (num1[i]) - ord ( '0' ); i - = 1 if j > = 0 : carry + = ord (num2[j]) - ord ( '0' ); j - = 1 result.append( str (carry % 10 )) carry / = 10 result.reverse() return "".join(result) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public : string addStrings(string num1, string num2) { string res = "" ; int m = num1.size(), n = num2.size(), i = m - 1, j = n - 1, carry = 0; while (i >= 0 || j >= 0) { int a = i >= 0 ? num1[i--] - '0' : 0; int b = j >= 0 ? num2[j--] - '0' : 0; int sum = a + b + carry; res.insert(res.begin(), sum % 10 + '0' ); carry = sum / 10; } return carry ? "1" + res : res; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步