|
处理大数时如果用整数法表示,就算是long int范围是-2^63~2^63-1,如果输入上千位,还是会挂掉,浪费空间。
所以说要用字符串的形式进行处理!
比如这道OJ
/*Sum of Numbers
Write a program which reads an integer and prints sum of its digits.
Input
The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.
The input ends with a line including single zero. Your program should not process for this terminal symbol.
Output
For each dataset, print the sum of digits in x.*/
一开始用整数法,挂掉
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
while(true){
long long int a;
int r, s=0;
cin>>a;
if(a==0)
break;
else{
while(a>0){
r = a % 10;
s = s + r;
a = a / 10;
}
cout<<s<<endl;
}
}
cout<<endl;
return 0;
}
换用字符串的方法,A了
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char a[1001];
while(cin>>a, strcmp(a,"0")){ // 输入为0时结束程序
int n = 0;
for(int i=0;i<strlen(a);i++) //将字符转换成整数
n += a[i] - '0';
cout<<n<<endl;
}
return 0;
}
注意一下字符串怎么处理输入结束标识符的 |