PTA甲级-1005 Spell It Right c++

题目内容

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

一、题干大意

给出一个非负的整数,范围在0~10^100,需要你将所有位上的字符加起来,然后用英语输出。

二、题解要点

  • 简单来说就是先把输入的数一个个分开加起来,然后把最后加起来的总和再分开,用英语输出

三、具体实现

#include <iostream>
#include <string>

using namespace std;

string turnEnglish(int num);

int main() {
    string n; //用于接收输入的字符串,因为数字过大,如果采用其他类型测试点6会过不了
    int sum = 0; //用来计算输入数字的总和
    string theResult = ""; //最后输出的结果

    cin >> n;

    /*计算输入数字的各位相加总和*/
    for (int i = 0; i < n.length(); ++i) {
        sum += (n[i] - '0');
    }

    /*将总和转化为英语*/
    do {
        theResult = turnEnglish((sum % 10)) + " " + theResult;
        sum /= 10;
    } while (sum != 0);

    /*由于每次转化都会有一个空格,所以最后需要去掉这个空格*/
    theResult = theResult.substr(0, theResult.length() - 1);
    cout << theResult << endl;

}

/***
 * 用于数字转英语的函数
 * @param num
 * @return
 */
string turnEnglish(int num) {
    switch (num) {
        case 0:
            return "zero";
        case 1:
            return "one";
        case 2:
            return "two";
        case 3:
            return "three";
        case 4:
            return "four";
        case 5:
            return "five";
        case 6:
            return "six";
        case 7:
            return "seven";
        case 8:
            return "eight";
        case 9:
            return "nine";
        default:
            return "";
    }
}

总结

难度比较小。但是要注意以下几点:

  1. 这个数字的范围比较大,不能用数字类型的变量去接收;
  2. 如果输入了0也要做处理;
  3. 不要拼错单词。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值