[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 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.
找规律,每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 题目汇总