文章目录
总题解目录
[PAT- Advanced Level] 甲级题解目录(Advanced Level)
A1005 Spell It Right (20point(s))
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
Analysis
- 已知一个数字串。
- 求这个数字串每一位加起来的和,并且以英语单词的形式输出。
- 注意,因为给的数字可能很长,所以使用char数组来存储输入的数据。
C++ Code1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <string>
#include <stack>
using namespace std;
map<int, string> mp;
stack<string> st;
void init(){ //不用map的话可以使用二维char数组
mp[0] = "zero";
mp[1] = "one";
mp[2] = "two";
mp[3] = "three";
mp[4] = "four";
mp[5] = "five";
mp[6] = "six";
mp[7] = "seven";
mp[8] = "eight";
mp[9] = "nine";
}
const int maxn = 101;
int main(){
init();
char n[maxn];
int sum = 0;
scanf("%s", n);
int len = strlen(n);
for (int i = 0; i < len; i++)
sum += n[i] - '0';
do{ //不用栈的话倒着输出就行
st.push(mp[sum % 10]);
sum /= 10;
} while (sum != 0);
while (!st.empty()){
printf("%s", st.top().c_str());
st.pop();
if (!st.empty())
printf(" ");
}
printf("\n");
return 0;
}
C++ Code2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <stack>
#include <vector>
#define MAX_N 101
using namespace std;
// 这种loop-up table 比较适合全局变量
vector<string> digit2string = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int digit_sum(char num[]){
int result = 0, len = strlen(num);
for (int i = 0; i < len; i++)
result += num[i] - '0';
return result;
}
int main(){
char n[MAX_N];
stack<string> st;
scanf("%s", n); // 因为数字很大,所以不考虑用int接收初始数据
int sum = digit_sum(n);
do{ //不用栈的话倒着输出就行
st.push(digit2string[sum % 10]);
sum /= 10;
} while (sum != 0);
while (!st.empty()){
printf("%s", st.top().c_str());
st.pop();
if (!st.empty())
printf(" ");
}
printf("\n");
return 0;
}