• 树根 Digital root


    数根

    (又称数字根Digital root)是自然数的一种性质。换句话说。每一个自然数都有一个数根。数根是将一正整数的各个位数相加(即横向相加),若加完后的值大于等于10的话,则继续将各位数进行横向相加直到其值小于十为止,或是,将一数字反复做数字和,直到其值小于十为止,则所得的值为该数的数根

    比如54817的数根为7。由于5+4+8+1+7=25,25大于10则再加一次。2+5=7,7小于十。则7为54817的数根。

    百度百科:http://baike.baidu.com/link?

    url=FKQ337jynzKVjYV7X92BZOWW51nI6unO71jOTV1g7gnGKnChCWXkNHB4hqTUCmvrwbPh9voBvMAZcxca3ohAua

    维基百科:https://en.wikipedia.org/wiki/Digital_root

    leetcode: https://leetcode.com/problems/add-digits/

    leetcode原题:

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

    For example:

    Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

    Follow up:
    Could you do it without any loop/recursion in O(1) runtime?

    解题思路一:

    将数的每一位取出来再相加。再将和的每一位取出来相加。直到和为一个个位数。

    代码例如以下:

    class Solution {
    public:
        int addDigits(int num) {
            if(num/10==0) return num;
            int res=0;
            while(num/10!=0)
            {
                res=0;
                 while(num)
               {
                int temp=num%10;
                res+=temp;
                num/=10;
               }
               num=res;
            }
           
            return res;
        }
    };
    解题方法二:

    採用有限域的相关知识:

    代码例如以下:

    class Solution {
    public:
        int addDigits(int num) {
           return 1+(num-1)%9;
        }
    };




  • 相关阅读:
    多线程的几种实现方法详解
    Java线程编程中isAlive()和join()的使用详解
    MyEclipse在不同编辑面间快速切换
    MyEclipse中设置代码块快捷键
    MyEclipse设置文件编码
    Oracle安装后遇到错误:The Network Adapter could not establish the connection
    Java中的Runtime类
    Java中接口的特点
    Java中三种常见的注释(注解) Annotation
    Java中的泛型
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/6934126.html
Copyright © 2020-2023  润新知