C++ solution with comments


  • 0
    R

    class Solution {
    public:
    int addhelp(string str){ //A helper function to add two digits;

        int res = 0;
        for(int i=0; i<str.length(); i++){
            int value;
            res +=str[i] -'0';
        }
        return res;
    }
    int addDigits(int num) {
        if(num <= 9) return num;     //Base case if the input less than 10 just return the value;
        int val = 0;
        string str;
        while(num > 9){                  // Add 2 digits until they become one digit;
                str = to_string(num);
                num = addhelp(str);
                
            }
        
        return num;
    }
    

    };


Log in to reply
 

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