描述
以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
数据范围:len(s),len(t) \le 100000len(s),len(t)≤100000,字符串仅由’0’~‘9’构成
要求:时间复杂度 O(n)O(n)
示例1
输入:
“1”,“99”
复制
返回值:
“100”
复制
说明:
1+99=100
示例2
输入:
“114514”,""
复制
返回值:
“114514”
#include<iostream>
#include<bits/stdc++.h>
#include<algorithm>
#include<string>
#include<stack>
using namespace std;
string solve(string s, string t) {//10 999
int len_i=s.size()-1;//2-1=1
int len_j=t.size()-1;//3-1=2
if(len_i<len_j) swap(s,t),swap(len_i,len_j);//s=999 t=10 len_i=2 len_j=1
int temp=0;
int carry=0;//控制进位
int c=len_i-len_j;//2-1=1
while(c>0){
t='0'+t;//不够位数的数字前面补0 1--->010
c--;
}
//999 + 010
for(int i=len_i;i>=0;i--){//len_i=2
temp=s[i]-'0'+t[i]-'0'+carry;//temp=9+0+0=9 temp=9+1+0=10 temp=9+0+1=10
if(temp>=10){
temp-=10;// temp=10-10=0 temp=10-10=0
carry=1;
}else{
carry=0;
}
s[i]=temp+'0';//s[2]=9 s[1]=temp=0 s[0]=temp=0 //009
}
if(carry==1){//carry=
s='1'+s;//1 009=1009
}
return s;
}
int main(){
string s,t;
cin>>s>>t;//10 999 1009
cout<<solve(s,t);
}