【每天一道PAT】1005 Spell It Right

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.

思路

已知读取的数据最大到100位, 因此使用字符串读取;
计算出总和后再将sum的每位数字存入动态数组中,由之前定义的数字字符串数组,双重映射,输出sum的每位数字的英文。

#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
vector<int> nums;
char num[10][20] ={"zero", "one", "two", "three", "four"
                   , "five", "six", "seven", "eight", "nine"};
int main()
{
    char N[101] = {0};
    scanf("%s", N);
    int len = strlen(N);
    int sum = 0;
    for (int i = 0; i < len; ++i)
    {
        sum+= N[i]-'0';
    }
    do
    {
        nums.push_back(sum%10);
        sum /=10;
    }while(sum !=0);
    for (int j = nums.size() - 1; j >= 0 ; --j)
    {
        printf("%s", num[nums[j]]);
        if(j != 0)printf(" ");
    }

}

posted @ 2020-04-02 12:05  XinyuLee  阅读(104)  评论(0编辑  收藏  举报