Is this Java solution fine?


  • 0
    S
    public class Solution {
        public int addDigits(int num) {
            if (num < 10) {
                return num;
            }
            int total = 0;
            while (num > 0) {
                total += num % 10;
                num /= 10;
            
                if (num == 0) {
                    if (total < 10) {
                        return total;
                    }
                    num = total;
                    total = 0;
                }
            }
            return -1;
        }
    

    }


  • 0
    O

    Here is my Java code, not an easy problem for me.

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

Log in to reply
 

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