zoukankan      html  css  js  c++  java
  • [LeetCode] 258. 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.

    找规律,每9个一循环(1~9),res = (num - 1) % 9 + 1

    数根是将一正整数的各个位数相加(即横向相加),若加完后的值大于10的话,则继续将各位数进行横向相加直到其值小于十为止[1],或是,将一数字重复做数字和,直到其值小于十为止,则所得的值为该数的数根。

    in out   in out
    0   0    10  1
    1   1    11  2
    2   2    12  3
    3   3    13  4
    4   4    14  5
    5   5    15  6
    6   6    16  7
    7   7    17  8
    8   8    18  9
    9   9    19  1

    Java: Trivial and naive

    public class Solution {
        public int addDigits(int num) {
            while (num > 9) {
                num = getInt(num);
            }
            return num;
        }
    
        private int getInt(int num) {
            int result = 0;
            while (num >= 10) {
                result += num % 10;
                num /= 10;
            }
            result += num;
            return result;
        }
    }
    

    Java: T: O(1), S: O(1)

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

    Python: Trivial and naive

    class Solution:
        def addDigits(self, num):
            while num > 9:
                c = 0
                while num:
                    c += num % 10
                    num /= 10
                num = c
            return num

    Python: T: O(1), S: O(1)

    class Solution:
        def addDigits(self, num):
            return (num - 1) % 9 + 1 if num > 0 else 0
    

    C++: Trivial and naive

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

    C++: T: O(1), S: O(1)

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

    All LeetCode Questions List 题目汇总

      

  • 相关阅读:
    ADO中的多层次数据集,类似于dataset
    工作流的设计
    Socket bind系统调用简要分析
    linux Network Address Translation NAT 转载 还需要整理
    生活20190602
    磁盘空间满的问题
    linux netfilter nat 实现 转载
    Socket 套接字的系统调用
    linux 网络编程 基础
    学习linux,不要找别人了,我有东西要发
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8507117.html
Copyright © 2011-2022 走看看