leetcode 258. Add Digits

传送门

258. Add Digits

My Submissions
Total 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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Show Hint 

    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 Tags
    Show Similar Problems
    Have you met this question in a real interview? 
    Yes
     
    No
     

    Discuss

    思维题,找找规律,详见代码:

     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 };
    原文地址:https://www.cnblogs.com/njczy2010/p/5192716.html