zoukankan      html  css  js  c++  java
  • HDU 1013 Digital Roots

    Digital Roots

    Problem Description
    The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

    For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.
     
    Input
    The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.
     
    Output
    For each integer in the input, output its digital root on a separate line of the output.
     
    Sample Input
    24
    39
    0
     
    Sample Output
    6
    3
     

     题意:输入一个整数, 计算这个整数各个位置上的数字之和,如果得到的这个数是各位数,那么这个各位数就是输入的整数的字根。如果得到的这个数不是个位数,那么再求这个数的字根。

    分析:有几点需要注意的

      1、输入的这个整数在不在int型数据里面,它是几位数,根据题意和经验可得,这个数很大,所以要用数组。

      2、如果输入的数本身是各位数该怎么处理——输出它本身。

      3、退出循环的判断语句该怎么写?

    AC源代码(C语言):

     1 #include<stdio.h>
     2 
     3 int main()
     4 {
     5     int i,a,RootSum;
     6     char s[1000];
     7     while(scanf("%s",s)&&(s[0]!='0'||s[1]!='\0'))             /*==与!=要分清.最重要的是s[0]!='0'||s[1]!='\0'不能写成s[0]!='0'&&s[1]!='\0',因为后面的写法把输入个位数的情况也当做非法数据处理了!!!!!*/
     8         {
     9             a = 0;
    10             RootSum = 0;
    11             for(i = 0;s[i]!='\0';i++)
    12             {
    13                 RootSum+=s[i]-'0';            /*千万要减去‘0’,因为减去‘0’也就是48后所得正好是整数,而且就是s[i]存放的数字!*/
    14             }
    15             while(RootSum<=0||RootSum>=10)
    16             {
    17                 while(RootSum)
    18                 {
    19                     a+=RootSum%10;
    20                     RootSum/=10;
    21                 }
    22                 RootSum=a;
    23                 a=0;              /*少了这一句,当输入的数字根大于9的时候,程序死循环!!!!!*/
    24             }
    25             printf("%d\n",RootSum);
    26         }
    27     return 0;
    28 }
    29 
    30 /*提交错误原因:输入 的数据不再整数范围内,要用字符数组。否则输入时会死循环,也就是提示的超时!*/

    2013-04-23

  • 相关阅读:
    IDEA2019破解版安装
    Docker (一)安装与基本命令
    js导出PDF
    python入门笔记一安装
    微信内关闭当前页面
    微信一些网页
    内网穿透工具:钉钉HTTP内网穿透使用详解
    html生成二维码,qr
    IDEA无法正常启动(打不开&报错)
    微信测试号
  • 原文地址:https://www.cnblogs.com/fjutacm/p/3038717.html
Copyright © 2011-2022 走看看