首页 > 其他 > 详细

[LeetCode#258]Add Digits

时间:2015-09-01 10:21:42      阅读:187      评论:0      收藏:0      [点我收藏+]

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);
    }
}

 

[LeetCode#258]Add Digits

原文:http://www.cnblogs.com/airwindow/p/4774854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!