Recursive Solution


  • 0
    H
    public int addDigits(int num) {
        if(num < 0) return num;
        if ((num + "").length() == 1){
            return num;
        }
        int sum = 0;
        String s = num +"";
        for(int i = 0; i < s.length(); i++){
            sum += s.charAt(i) - '0';
        }
        
        return addDigits(sum);
    }

  • 0
    B

    Really no need to use a string.

    public int addDigits(int num) {
        if (num < 10)
            return num;
        int res = num % 10;
        while ((num /= 10) > 0)
            res += num % 10;
        return addDigits(res);
    }

Log in to reply
 

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