ID | Title | Difficulty | |
---|---|---|---|
Loading... |
258. Add Digits
Easy
LeetCode
Math, Simulation, Number Theory
Problem
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
Code
class Solution {
public int addDigits(int num) {
if(num < 10) return num;
int res = 0;
while(num != 0) {
res += num % 10;
num /= 10;
}
return addDigits(res);
}
}
class Solution:
def addDigits(self, num: int) -> int:
if num < 10:
return num
res = 0
while num != 0:
res += num % 10
num //= 10
return self.addDigits(res)
digit root 问题
class Solution:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else (num - 1) % 9 + 1
按 <- 键看上一题!
257. Binary Tree Paths
按 -> 键看下一题!
259. 3Sum Smaller