PTA甲级1005 Spell It Right (20分)

首先,先贴柳神的博客

https://www.liuchuo.net/ 这是地址

想要刷好PTA,强烈推荐柳神的博客,和算法笔记

原题如下

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

题目大意

就是给一个数字,要你吧数字上的各位累加求和

代码如下

#include<iostream>
#include<cstring>
using namespace std;
int main(void) {
    string a;
    int Sum = 0;
    string b[10] = { "zero","one","two","three","four","five","six","seven","eight","nine" };
    cin >> a;
    for (char i : a) {
        Sum += i - 48;
    }
    int i = 0;
    while (Sum) {
        int t = Sum % 10;
        a[i] = t+48;
        i++;
        Sum /= 10;
    }
    i--;
    while (i >0) {
        cout << b[a[i]-48]<<" ";
        i--;
    }
    if (i == 0)
        cout << b[a[i] - 48];
    else
        cout << "zero";
    return 0;
}

柳神的代码如下

#include <iostream>
using namespace std;
int main() {
    string a;
    cin >> a;
    int sum = 0;
    for (int i = 0; i < a.length(); i++)
        sum += (a[i] - '0');
    string s = to_string(sum);  //可以把整数转换为string类型
    string arr[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    cout << arr[s[0] - '0'];
    for (int i = 1; i < s.length(); i++)
        cout << " " << arr[s[i] - '0'];
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/a-small-Trainee/p/12386823.html