zoukankan      html  css  js  c++  java
  • PAT(A) 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
    
    #include <cstdio>
    #include <cstring>
    /*给出一个数字,求出每位数字的总和,并用英文表示总和的每一位
      N<=10^100=10...0 最大数位和为每位都是9的情况,共100位 => 最大数位和为100*9
    */
    //数字与单词的对应
    char num[10][10]={"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    char str[105];        //初始字符串101位(10^100)+1位() => 数组至少需要开102位
    int digitInt[10];       //把sum写到digitInt[]里
    char digitChar[10];     //把sum写到digitChar[]里
    
    void dfs(int n){        //法二: 递归
      
    if(n/10==0){ printf("%s", num[n%10]); return; } dfs(n/10); printf(" %s", num[n%10]); } int main() { gets(str); int len=strlen(str); //len: str的长度 int sum=0, numlen=0; //sum: str的数位之和; numlen: 计量sum的长度 for(int i=0; i<len; i++) sum += str[i]-'0'; //累加s的数位 => sum //法一:数存入数组+输出 if(sum==0) //sum==0: 特判输出num[0] printf("%s", num[0]); else{     //sum!=0: 将数sum的每一位存放到digitInt[]中并输出每位对应的英文 while(sum){ digitInt[numlen++]=sum%10; //sum: 123 => digitInt[]: 3 2 1 sum /= 10; } for(int i=numlen-1; i>=0; i--){ //从高位到低位输出digitInt[i]对应的英文 printf("%s", num[digitInt[i]]); if(i) printf(" "); //控制格式 } /* //把sum写到digitChar[]里(法二) sprintf(digitChar, "%d", sum); //sprintf(): 将sum按%d写入char数组digitChar[]中 numlen=strlen(digitChar); for(int i=0; i<numlen; i++){ //从高位到低位输出digitChar[i]对应的英文 printf("%s", num[digitChar[i]-'0']); if(i!=numlen-1) printf(" "); //控制格式 } */ } //法二:递归 //dfs(sum);
       return 0; }
  • 相关阅读:
    jQuery 核心
    Js实现内容向上无缝循环滚动
    浅析CSS postion属性值用法
    JS原生Ajax请求
    详解SQL集合运算
    Windows上开启IIS
    poj 4618 暴力
    hdu 4614 线段树
    poj 3468 线段树
    hdu 1698 线段树成段更新
  • 原文地址:https://www.cnblogs.com/claremore/p/6548694.html
Copyright © 2011-2022 走看看