Problem : https://leetcode.com/problems/add-digits/
A naive solution:
class Solution:
def addDigits(self, num: int) -> int:
sums = 0
while num > 0:
sums += num % 10
num = num // 10
return sums if sums < 10 else self.addDigits(sums)
A mathematic solution:
class Solution:
def addDigits(self, num: int) -> int:
if num == 0:
return 0
return 9 if num % 9 == 0 else num % 9
Assume there is a 3 digits number abc.
Then abc = a * 100 + b * 10 + c
Let sums = a + b + c, then abc - sums = 99 * a + 9 * b
So, sums = abc - (99 * a + 9 *b)
Because (99 * a + 9 * b) is divisible by 9, sums % 9 = abc % 9.
So we return num % 9 as result. If num % 9 = 0, return 9. As we only need to repeatedly add all digits until the result has only one digit.
No comments:
Post a Comment