zoukankan      html  css  js  c++  java
  • [LeetCode]64. Add Digits数根

    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?

    Hint:

    1. A naive implementation of the above process is trivial. Could you come up with other methods?
    2. What are all the possible results?
    3. How do they occur, periodically or randomly?
    4. You may find this Wikipedia article useful.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     
    解法1:利用to_string库函数,只要输入整数的数字个数大于1,则执行自身数字相加的过程。
    class Solution {
    public:
        int addDigits(int num) {
            string s = to_string(num);
            while (s.size() > 1) {
                int tmp = 0;
                for (int i = 0; i < s.size(); ++i)
                    tmp += s[i] - '0';
                s = to_string(tmp);
            }
            return stoi(s);
        }
    };

    或者直接分别取出某位累加:

    class Solution {
    public:
        int addDigits(int num) {
            while (num >= 10) {
                int sum = 0;
                while (num > 0) {
                    sum += num % 10;
                    num /= 10;
                }
                num = sum;
            }
            return num;
        }
    };

    解法2:参考维基百科Digital root

    It helps to see the digital root of a positive integer as the position it holds with respect to the largest multiple of 9 less than it. For example, the digital root of 11 is 2, which means that 11 is the second number after 9. Likewise, the digital root of 2035 is 1, which means that 2035 − 1 is a multiple of 9. If a number produces a digital root of exactly 9, then the number is a multiple of 9.

    With this in mind the digital root of a positive integer n may be defined by using floor function lfloor x
floor , as

    dr(n)=n-9leftlfloorfrac{n-1}{9}
ight
floor.

    不难写出代码:

    class Solution {
    public:
        int addDigits(int num) {
            return (num - 1) % 9 + 1; //return num - 9 * ((num - 1) / 9);
        }
    };
  • 相关阅读:
    YTU 2959: 代码填充--雨昕学矩阵
    YTU 2958: 代码填充--雨昕学画画
    YTU 2960: 改错题--小鼠标,你要干什吗?
    YTU 2975: 我的编号
    YTU 2979: MathBook类--多态
    linux命令学习:echo详解,格式化输出,不换行输出
    linux shell date 时间运算以及时间差计算方法
    C语言中mktime函数功能及用法
    Posix线程编程指南(3)
    Posix线程编程指南(2)
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4946841.html
Copyright © 2011-2022 走看看