zoukankan      html  css  js  c++  java
  • 甲级1005 Spell It Right

    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


    分析:先按字符读入,每次读入都将该字符与'0'相减,然后得到sum。将sum输入到字符串流中,再用这个字符串流当作字符输出,输出来的字符再转为最后结果
    这里sum的处理也可以用to_string(要包含<string>头文件),然后遍历这个字符串形式的sum,转成结果。
    这里在输入的地方遇到了一个坑,如果用while (scanf("%c",&char_in) != EOF)来读取输入,就会报一堆错,大概是因为在输入的末尾不一定直接是EOF,也有可能是换行啊什么的


    两份代码如下:

    1、使用了字符串流的
     1 #include <iostream>
     2 #include <sstream>
     3 using namespace std;
     4 
     5 string digit[10]= { "zero","one","two","three","four","five",
     6                     "six","seven","eight","nine" };
     7 
     8 int main()
     9 {
    10     string input;
    11     char char_in;
    12     int sum = 0;
    13     cin >> input;
    14     for (auto it = input.begin(); it != input.end(); it++)
    15     {
    16         sum += *it - '0';
    17     }
    18     stringstream ss;
    19     ss << sum;
    20     bool flag = false;
    21     while (ss >> char_in)
    22     {
    23         if (flag == false)    flag = true;
    24         else cout << " ";
    25         cout << digit[char_in - '0'];
    26     }
    27     return 0;
    28 }
    
    
    
     
    
    
    
     2、使用to_string的
     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 string digit[10]= { "zero","one","two","three","four","five",
     6                     "six","seven","eight","nine" };
     7 
     8 int main()
     9 {
    10     string input;
    11     int sum = 0;
    12     cin >> input;
    13     for (auto it = input.begin(); it != input.end(); it++)
    14     {
    15         sum += *it - '0';
    16     }
    17     string sum_str = to_string(sum);
    18     bool flag = false;
    19     for (auto it = sum_str.begin(); it != sum_str.end(); it++)
    20     {
    21         if (flag == false)    flag = true;
    22         else cout << " ";
    23         cout << digit[*it - '0'];
    24     }
    25     return 0;
    26 }
    
    
    
     
  • 相关阅读:
    [转]IUnkown生命周期管理
    [转] com 基本数据类型
    Centos 7 修改开机等待时间 Alex
    乌班图的安装常用命令 Alex
    Ubuntu切换root用户 Alex
    乌班图开启关闭防火墙 Alex
    Ubuntu远程root用户登录 Alex
    Centos 8 更改为阿里云源 Alex
    LVS调度之搭建NAT模型实现 Alex
    解决挂载mount: wrong fs type, bad option, bad superblock on Alex
  • 原文地址:https://www.cnblogs.com/jiongyy0570/p/10290654.html
Copyright © 2011-2022 走看看