题目
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 (≤10
100 ).
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
题目大意
计算所给数字各位之和,然后用英文输出和的每一位
代码和思路
思路
整体来讲很简单,从高位到低位输出和的每一位,很自然的想到利用stack结构。剩下的就是对输入输出进行处理
输入数N可以直接处理为字符串,也较为方便。
因为题目是非负整数,所以要格外注意零是否在自己的代码中需要进行特殊处理
代码
#include<cstdio>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<int> q;
void Print1(int k) {
switch (k) {
case 1:
printf(" one");
break;
case 2:
printf(" two");
break;
case 3:
printf(" three");
break;
case 4:
printf(" four");
break;
case 5:
printf(" five");
break;
case 6:
printf(" six");
break;
case 7:
printf(" seven");
break;
case 8:
printf(" eight");
break;
case 9:
printf(" nine");
break;
case 0:
printf(" zero");
break;
}
}
void Print2(int k) {
switch (k) {
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
case 0:
printf("zero");
break;
}
}
int main() {
string str;
int sum = 0;
int temp;
int i = 0;
cin >> str;
i = str.length();
for (int j = 0; j < i; j++) {
temp = str[j] - '0';
sum += temp;
}
if(sum == 0){
printf("zero");
return 0;
}
while (sum != 0) {
temp = sum % 10;
sum = sum / 10;
q.push(temp);
}
temp = q.top();
Print2(temp);
q.pop();
while (!q.empty()) {
temp = q.top();
Print1(temp);
q.pop();
}
return 0;
}
因为懒得对输出进行特殊处理了。。。所以直接复制了两遍Print函数,不影响效率。
因为使用了栈这样的数据结构,而且直接在代码第98行也就是 temo = q.top() 而且在上面的读入每位的过程中以0为循环边界,所以要对0进行特殊处理。
在对输入的处理中使用了sring然后转化,这里其实还有别的方法。