[PAT甲级]1005. Spell It Right (20)(求数字各个位上的和,英文输出)

1005. Spell It Right (20)

原题链接

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

题目大意:

  • 输入一个数N(小于10的100次方),计算N各个位上的数字和sum
  • 将sum用英文输出,两个英文单词中间用空格隔开,最后一位不要有多余空格

思路:

  • 直接输入用字符串表示,遍历字符串,求出各个字符的和,最终输出

代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string v[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    string s;
    getline(cin, s);
    int sum = 0;
    for(int i=0; i<s.size(); i++){
        sum += s[i]-'0';
    }
    string res = "";
    while(sum >= 10){
        res = " " + v[sum%10] + res;
        sum /= 10;
    }
    if(sum < 10)
        res = v[sum] + res;
    cout << res << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/whl_program/article/details/77387732