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.
Input Specification:
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.
Sample Input:
12345
Sample Output:
one five
思路1:
首先建立一个从数字0~9到字符串“zero”~“nine”的一个map映射,将输入的数据按照string类型的数据进行读入。将输入的字符串的每一位减去‘0’再加起来就得到了每一位相加的和sum。利用栈,从sum的个位开始,将每一位数字对应的字符串映射压入栈中,最后反向输出即可。这里要注意的是,0作为特殊情况要单独考虑,不能漏掉。这里有几个坑,一个是string是属于C++的类,只能用cin输入,而不能用scanf,还有map作为C++的stl模板库里面的函数,也是不能用printf来进行输出,要用cout。千万记住!
代码:
#include <iostream>
#include<cstring>
#include<map>
#include<string>
#include<stack>
using namespace std;
const int maxn = 110;
char num[maxn];
map<int, string>intToString;
stack<string>ans;
int main()
{
intToString[0] = "zero"; intToString[1] = "one"; intToString[2] = "two"; intToString[3] = "three"; intToString[4] = "four";
intToString[5] = "five"; intToString[6] = "six"; intToString[7] = "seven"; intToString[8] = "eight"; intToString[9] = "nine";
//cout << intToString[9]<<endl;
//printf_s("%s", intToString[1]);
int length = 0,sum=0;
string num ;
cin >> num;
length = num.length();
for (int i = 0; i < length; i++)
{
sum += num[i] - '0';
}
int temp;
//cout << sum << endl;
if (sum == 0)
{
cout << "zero";
return 0;
}
while (sum!=0)
{
temp = sum % 10;
sum /= 10;
ans.push(intToString[temp]);
}
//cout << ans.size() << endl;
if (ans.empty() == false)
{
cout<<ans.top();
ans.pop();
while (!ans.empty())
{
cout << " " << ans.top();
ans.pop();
}
}
return 0;
}
思路2(柳神):
- 求出每⼀一位相加的和sum
- 将sum转换为string s
- 将string s的每⼀一位输出对应的英⽂文读⾳音
这里有一个新的函数学习一下, to_string()可以将数字转化为相应的字符串。
string num=to_string(12345);
代码:
#include <iostream>
#include<string>
using namespace std;
int main()
{
string a;
int sum=0;
cin >> a;
for (int i = 0; i < a.length(); i++)
{
sum += a[i] - '0';
}
string s = to_string(sum);
string str[10] = { "zero","one","two","three","four","five","six","seven","eight","nine" };
cout << str[s[0]-'0'];
for (int i = 1; i < s.length(); i++)
{
cout << " " << str[s[i] - '0'];
}
return 0;
}