My 3 C++ solutions (8 ms)


  • 0
    D

    The first one I got is the trivial one with while loop to sum all the digits

    class Solution {
    public:
        int addDigits(int num) {
            while(num>9)
            {
                int temp =0;
                while(num)
                {
                    temp += num%10;
                    num /= 10;
                }
                num = temp;
            }
            return num;
        }
    };
    

    Then I tried to find a way to avoid the inner loop (that sums all the digits) and then got the following one. The basic idea behind it is to do the sum of all digits indirectly. Say num = a0 + a1x10 + a2x100 + a_n x10^n, then num - (num/10)*9 = a0 + a1 + a2x10 + a3x100 + a_nx10^(n-1). Through while loop, eventually, the remaning digit is what we want.

    class Solution {
    public:
        int addDigits(int num) {
            while(num>9)    num -=(num/10) *9;
            return num;
        }
    };
    

    But I couldn't get the final non-loop solution by myself after 30-min struggle and gave up. With the hint, it is trivial to get the following solution

    class Solution {
    public:
        int addDigits(int num) {
            return num%9?num%9:(num!=0?9:0);
        }
    };

  • 0
    M
    class Solution {
    public:
        int addDigits(int num) {
            if(num<=9)
            return num;
            int sum=0;
            int temp=num;
            while(temp>0)
            {
                sum+=temp%10;
                temp=temp/10;
            };
            return addDigits(sum);
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.