Simple java solution with modulo operation


  • 1
    Z

    For instance, an integer xyz = 100x + 10y +z, xyz % 9 = 99*x + 9*y + (x + y + z) % 9 = (x + y + z) % 9. Thus here is my code:

    public int addDigits(int num) {
            if (num == 0) return 0;
            while (num > 9) num %= 9;
            return num == 0 ? 9 : num;
        }
    

  • 0
    W

    why is adding up the digits of xyz, such as x+y+z the same as (x + y + z) % 9?


Log in to reply
 

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