首页 > 代码库 > LeetCode 258 Add Digits
LeetCode 258 Add Digits
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 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Could you do it without any loop/recursion in O(1) runtime?
Summary:
给出一个整型数,反复求出它各个位数之和,直至和小于10。
能否不使用循环和递归,复杂度为O(1)。
Analysis:
1、常规方法:
2、Hint提示:Digital Root (from:Wikipedia-https://en.wikipedia.org/wiki/Digital_root)
Digital roots can be calculated with congruences in modular arithmetic rather than by adding up all the digits, a procedure that can save time in the case of very large numbers.
It helps to see the digital root of a positive integer as the position it holds with respect to the largest multiple of 9 less than the number itself. For example, the digital root of 11 is 2, which means that 11 is the second number after 9. Likewise, the digital root of 2035 is 1, which means that 2035 ? 1 is a multiple of 9. If a number produces a digital root of exactly 9, then the number is a multiple of 9.
The formula is:
or
1 class Solution { 2 public: 3 int addDigits(int num) { 4 if (num <= 9) { 5 return num; 6 } 7 else if (num % 9 == 0) { 8 return 9; 9 } 10 else { 11 return num % 9; 12 } 13 } 14 };
or
1 class Solution { 2 public: 3 int addDigits(int num) { 4 return 1 + ((num - 1) % 9); 5 } 6 };
LeetCode 258 Add Digits