PAT甲级1005 Spell It Right (20分)|C++实现

tech2022-07-05  186

一、题目描述

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( ≤ 1 0 100 \leq10^{100} 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

二、解题思路

这道题难度不大,要注意的是,题目给出的数字范围很大,所以我们用字符串来存储。定义一个字符串数组,对应0~9的英文。定义一个函数,计算每位数字之和。随后,将答案转化成字符串,遍历,输出字符串数组中的单词。

三、AC代码

#include<iostream> #include<cstdio> #include<string> #include<algorithm> #include<cstring> using namespace std; string mk[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; int cal(string str) { int ans=0; for(int i=0; i<str.length(); i++) ans += str[i] - '0'; return ans; } int main() { string str; cin >> str; int ans = cal(str); string s = to_string(ans); for(int i=0; i<s.length(); i++) { if(i == 0) cout << mk[s[i]-'0']; else cout << " " << mk[s[i] - '0']; } return 0; }
最新回复(0)