zoukankan      html  css  js  c++  java
  • 树根

    树根

    Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
    Appoint description: 

    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
     
    是位数上的和相加,一直到和为一位数:
    你可以这么写:
    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <algorithm>
    #include <vector>
    #include <queue>
    #include <cmath>
    #include <stack>
    #include <cstring>
    using namespace std;
    #define INF 0xfffffff
    #define maxn 1200
    #define min(a,b) (a<b?a:b)
    #define max(a,b) (a>b?a:b)
    
    int Root(int n)
    {
        if(n < 10)
        {
            return n;
        }
        int a = 0;
    
        while(n)
        {
            a += n%10;
            n /= 10;
        }
        Root(a);  //递归,因为要做的步骤一样
    }
    
    int main()
    {
        char str[maxn];
        int n;
        while(cin >>str,  strcmp(str, "0"))
        {
            n = 0;
            for(int i=0; str[i]; i++)
                n += str[i] - '0';
    
            n = Root(n); // 就是正常思维一步步求树根
    
            cout << n << endl;
        }
        return 0;
    }


    你也可以这么写:
    #include<stdio.h>
    #include<string.h>
    char s[1010];
    int main()
    {
        int sum,i,len,x;
        while(gets(s)&&s[0]!='0')
        {
            sum=0;
            len=strlen(s);
            for(i=0;i<len;i++)
                sum+=s[i]-'0';
            x=sum%9; // 求余9是因为十进制满10进1,38%9 = 2;38的树根是,3 + 8 = 11, 1 + 1 = 2,是2;自己悟=。=||
            if(x==0) x+=9;
            printf("%d
    ",x);
        }
        return 0;
    }
    让未来到来 让过去过去
  • 相关阅读:
    2020/12/27
    2020/12/25 the light
    2020/12/25
    2020/12/23
    2020/12/22
    美加大量银行用户遭攻击,这些黑客到底牛到什么程度?
    揭秘马云的蚂蚁科技“整改”计划
    大众集团成功研发:可移动的电动汽车充电器,网友:太方便了
    东方联盟郭盛华的江湖往事
    5种方法!疫情期间防御恶意软件,网络钓鱼和诈骗
  • 原文地址:https://www.cnblogs.com/Tinamei/p/4468288.html
Copyright © 2011-2022 走看看