先反转,再相加,过程中记录一下进位
c++
class Solution { public: string solve(string s, string t) { reverse(s.begin(),s.end()); reverse(t.begin(),t.end()); string ans = ""; int len = max(s.length(),t.length()); int d = 0;//记录进位 for(int i = 0 ; i < len ; i++) { int si= 0,ti = 0; if(i<s.length()){ si = s[i]-'0'; } if(i<t.length()){ ti = t[i]-'0'; } ans+=(si+ti+d)%10+'0'; d = (si+ti+d)/10; } if(d) { ans+=d+'0'; } reverse(ans.begin(),ans.end()); return ans; } };
java
import java.util.*; public class Solution { public String solve (String s, String t) { StringBuffer s1 =new StringBuffer(s); s1 = s1.reverse(); StringBuffer t1 =new StringBuffer(t); t1 = t1.reverse(); StringBuffer ans =new StringBuffer(); int len = Math.max(s.length(),t.length()); int d = 0;//记录进位 for(int i = 0 ; i < len ; i++) { int si= 0,ti = 0; if(i<s.length()){ si = s1.charAt(i)-'0'; } if(i<t.length()){ ti = t1.charAt(i)-'0'; } ans.append((char)((si+ti+d)%10+'0')); d = (si+ti+d)/10; } if(d>0) { ans.append((char)(d+'0'));} return ans.reverse().toString(); } }
python
class Solution: def solve(self , s , t ): s = s[::-1] t = t[::-1] ans = '' length = max(len(s),len(t)); #记录进位 d = 0 for i in range(length): si = 0 ti = 0 if i<len(s): si = int(s[i]) if i<len(t): ti = int(t[i]) ans += str((si+ti+d)%10) d = (si+ti+d)//10 if d>0: ans += str(d) return ans[::-1]
java和python语言里其实是自带高精度实现的
java
import java.util.*; import java.math.BigInteger; public class Solution { public String solve (String s, String t) { BigInteger S = new BigInteger(s); BigInteger T = new BigInteger(t); return S.add(T).toString(); } }
python
class Solution: def solve(self , s , t ): return int(s)+int(t)