258. Add Digits
My SubmissionsTotal Accepted: 68661 Total Submissions: 142851 Difficulty: Easy
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
思维题,找找规律,详见代码:
1 class Solution { 2 public: 3 int addDigits(int num) { 4 if(num <= 9){ 5 return num; 6 } 7 else{ 8 if(num % 9 == 0){ 9 return 9; 10 } 11 else{ 12 return num % 9; 13 } 14 } 15 } 16 };