【PAT】PAT A1005 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.

Sample Input:

12345

Sample Output:

one five

题目大意

求给出的一个数各位数之和,用英文单词隔开,最后没有空格

思路1

最大数字为10^100,所以使用string存储数字。不断取余获得各位数之和,相加得到结果,在返过来取余输出这个结果的各位(使用dfs输出)即可。

代码1

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
string a[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
// 如果取余一次输出一个余数,那么与正确的结果正好是返过来的, 所以使用dfs反向输出
void f(int n){
    int next = n / 10;
    if(next > 0){
        f(next);
        printf("%c", ' ');
    }
    cout << a[n % 10];
}
int main(int argc, const char * argv[]) {
    int n = 0;
    string s;
    cin >> s;
    const unsigned long l = s.size();
    for(int i = 0; i < l; i++){
        n += s[i] - '0';
    }
    
    // 这里注意处理n为0的情况,否则会有一个点过不了
    if(n == 0) printf("zero");
    else f(n);
    return 0;
}

思路2

使用char数组来存储也是一样的,看个人喜好了,不适用dfs输出也可以将各位和的各位存放在一个数组里,然后遍历转换成英文单词输出。char数组的使用没有string那么方便,但是效率高一点,在这道题里没差了,3ms和5ms的区别。
我们粗略估计,当输入是9…999(100个9)的时候,它的和是900。也就是我们的最终结果最大是个三位数。
写程序的时候估计数值范围和数组的长度非常重要

代码2

#include <iostream>
#include <cstdio>
char a[10][10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int main() {
    int n = 0;
    char c[101];
    scanf("%s", c);
    
    int i = 0;
    while (c[i] != '\0') {
        n += c[i] - '0';
        i++;
    }
    
    // 将n的各位存在res[0], res[1]..res[len - 1]中
    int res[3];
    int len = 0;
    if(n > 0){
        while (n > 0) {
            res[len++] = n % 10;
            n /= 10;
        }
        printf("%s", a[res[len - 1]]);
        for(int j = len - 2; j >= 0; j--){
            printf(" %s", a[res[j]]);
        }
    }else{
        printf("zero");
    }
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值