Description
给你两个整数n,m,求从n到m之间所有数字之和,保证0<=n<=m
Input
只有一行包含两个整数n,m
Output
输出n到m之间所有数字之和
Sample Input
1 2
0 100000
Sample Output
3
5000050000
思路:对于大整数类的运算,只能当其为字符串处理,模拟运算过程。
Code:
#include <iostream>
#include <cstdio>
using namespace std;
string add(string a,string b){
long long int t,p=0,i=0,j=0;
string c="";
for(;i<a.length()||j<b.length();){
if(i<a.length()&&j<b.length())
t=(a[i++]-'0')+(b[j++]-'0')+p;//int
else if(i<a.length())
t=a[i++]-'0'+p;
else
t=b[j++]-'0'+p;
p=0;
if(t>9){
t-=10;p=1;
}
c+=t+'0';//int to char
}
if(p) c+=1+'0';//
return c;
}
string intTOstr(long long int i){
string t="";
while(i){
t+=i%10+'0';
i/=10;
}
return t;
}
int main(){
long long int n,m;
while(scanf("%lld%lld",&n,&m)!=EOF){
string t=intTOstr(n),p;
for(long long int i=n+1;i<=m;i++){
p=intTOstr(i);
t=add(t,p);
}
for(int i=t.length()-1;i>=0;i--) cout<<t[i];
cout<<endl;
}
return 0;
}