zoukankan      html  css  js  c++  java
  • [LeetCode#258]Add Digits

    Problem:

    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?

    Analysis:

    Note: all digits problem could be solved through underlying principle!
    For this problem, the best reference is:
    https://en.wikipedia.org/wiki/Digital_root
    
    The meaning of Digital root is, it actually measures the distance between num and the largest number(the largest multiple of 9 before it).
    E:
    The digital root of 11 is 2, the largest multiple of 9 before it is 9, the ditance is 11 - 9 = 2(just equal to digital root!)
    Thus we could directly compute digital root through the minus operation between num, and its leftmost mutiple of 9.
    The larget multiple of 9 before a number.
    9 * ((num - 1) / 9)
    
    use (num-1) is to in case num is just the largest multiple of 9. 
    for other cases, it is actually equal to num/9

    Solution:

    public class Solution {
        public int addDigits(int num) {
            if (num < 0)
                throw new IllegalArgumentException("the passed int num is illegal!");
            return num - 9*((num-1)/9);
        }
    }
  • 相关阅读:
    git 常用命令
    目录
    算法--双栈排序
    算法--栈的翻转练习题
    算法--双栈队列
    算法--可查询最值的栈练习题
    Spark算子--union、intersection、subtract
    Spark算子--take、top、takeOrdered
    Spark算子--countByKey
    Spark算子--SortBy
  • 原文地址:https://www.cnblogs.com/airwindow/p/4774854.html
Copyright © 2011-2022 走看看