[Oracle] LeetCode 415 Add Strings
作者:互联网
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger
). You must also not convert the inputs to integers directly.
Solution
其实就是高精度加法,这里按照竖式加法即可,其中 \(top\) 表示进位
点击查看代码
class Solution {
private:
string ans="";
public:
string addStrings(string num1, string num2) {
int n1 = num1.size();
int n2 = num2.size();
int top = 0;
int pos1=n1-1, pos2=n2-1;
while(1){
int s1=0, s2=0;
if(pos1>=0)s1=num1[pos1]-'0';
if(pos2>=0)s2=num2[pos2]-'0';
int sum = s1+s2+top;
if(sum<10){
ans= char('0'+sum)+ans; top=0;
}
else{
ans= char(sum%10+'0')+ans;top=1;
}
pos1--;pos2--;
if(pos1<0 && pos2<0) break;
}
if(top){
ans=char('0'+top)+ans;
}
//reverse(ans.begin(), ans.end());
return ans;
}
};
标签:string,num2,int,s2,415,Add,Oracle,pos2,num1 来源: https://www.cnblogs.com/xinyu04/p/16626339.html