Given a non-negative integer?N, your task is to compute the sum of all the digits of?N, and output every digit of the sum in English.
Each input file contains one test case. Each case occupies one line which contains an?N?(≤10100).
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
12345
Sample Output:
one five
乍一看这道题挺简单的,几行代码写完胸有成竹地点击提交时,发现竟然有两个测试点不通过?!
经过排查之后,发现了问题所在:
测试点2:当输入的数为0时,按照原来的算法是没有输出的,所以要单独处理,添加后的代码如下(仍为错误案例,请勿模仿哈,正确的往下看):
#include<iostream>
#include<vector>
using namespace std;
string ans[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main()
{
long num;
vector<int> digits;
scanf("%ld",&num);
while(num!=0)
{
int dig;
dig=num%10;
digits.push_back(dig);
num=num/10;
}
int sum=0;
for(int i=0;i<digits.size();i++)
{
sum+=digits[i];
}
if(sum==0)cout<<ans[0]<<endl;//Tip:输入的数为0时的单独处理
vector<int> str;
while(sum!=0)
{
int dig;
dig=sum%10;
str.push_back(dig);
sum=sum/10;
}
for(int i=str.size()-1;i>=0;i--)
{
cout<<ans[str[i]];
if(i!=0)cout<<" ";
else cout<<'\n';
}
return 0;
}
这样查漏补缺后测试点2是成功pass了,但是测试点4仍然是找不到问题所在。但总感觉可能是当输入的数值很大溢出的原因,所以随意输了一个大值测试了一下,果然,结果错了:
所以思来想去我又回去看了一遍题目,终于发现了这个坑,害!
咱们再来看一下题目里这个N的范围:
而 int , long , long long 各自的范围是:
unsigned int | 0~4294967295 | int | -2147483648~2147483647 | unsigned long | 0~4294967295 | long | -2147483648~2147483647 | long long的最大值 | 9223372036854775807 | long long的最小值 | -9223372036854775808 | unsigned long long的最大值 | 18446744073709551615 | __int64的最大值 | 9223372036854775807 | __int64的最小值 | -9223372036854775808 | unsigned __int64的最大值 | 18446744073709551615 |
所以这道题和我一样用数值做的,可以扣眼珠子了((′-_-)-_-)-_-)
正确的做法应该直接把输入的这个数当作字符串来处理
代码如下:
#include<iostream>
#include<string>
using namespace std;
string ans[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main()
{
string num;
cin>>num;
int sum=0;
//求和
for(int i=0;i<num.length();i++)
sum+=(num[i]-'0');
//数和字母转换
string s=to_string(sum);
cout<<ans[(s[0]-'0')];
for(int i=1;i<s.length();i++)
{
cout<<" "<<ans[(s[i]-'0')];
}
cout<<endl;
return 0;
}
运行结果如下:
这就非常简单了,这么水的题硬是被自己折腾的这么复杂还是错的,下次一定要好好看清题目了哈
?
|