[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 = 11, 1 + 1 = 2. Since 2 has o

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 = 11, 1 + 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:

A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

挺简单的一道题。

public int addDigits(int num) {
        if (num / 10 == 0)
            return num;
        int sum = 0;
        while (true) {
            sum += num % 10;
            num = num / 10;
            if (num == 0) {
                if (sum / 10 == 0)
                    return sum;
                num = sum;
                sum = 0;
            }
        }
    }

发人深省吧

1.逐位相加直到小于10

public int addDigits(int num) {
        while (num >= 10) {
            num = (num / 10) + num % 10;
        }
        return num;
    }

2.通过输入距离来发现规律

123456789 10 11 12 13 14 15

123456789 1 2 3 4 5 6

public int addDigits(int num) {
        return 1 + (num - 1) % 9;
    }
目录
相关文章
|
6月前
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
26 0
|
8月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
11月前
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
|
算法
LeetCode 423. Reconstruct Original Digits
给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9。按升序输出原始的数字。
80 0
LeetCode 423. Reconstruct Original Digits
LeetCode 415. Add Strings
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
67 0
LeetCode 415. Add Strings
LeetCode 402. Remove K Digits
给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。
55 0
LeetCode 402. Remove K Digits
LeetCode 258. Add Digits
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
52 0
LeetCode 258. Add Digits
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
54 0
LeetCode 241. Different Ways to Add Parentheses
LeetCode 67. Add Binary
给定两个二进制字符串,返回它们的总和(也是二进制字符串)。 输入字符串都是非空的,只包含字符1或0。
54 0
LeetCode 67. Add Binary
|
存储
Leetcode-Medium 2. Add Two Numbers
Leetcode-Medium 2. Add Two Numbers
52 0