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);
        }
    }
  • 相关阅读:
    用的fileupload组件实现的大文件上传
    手机刷机
    Bonferroni correction
    FTP 常用命令
    Oracle 10 参数配置说明
    Solaris 10 ftp,telnet,ssh,sendmail
    solaris10下安装oracle10g
    solaris10中安装oracle内核参数的调整
    matlab从txt/csv文件中读取一行
    SUN服务器Solaris10安装步骤
  • 原文地址:https://www.cnblogs.com/airwindow/p/4774854.html
Copyright © 2011-2022 走看看