Simple Explaination for the solution


  • 0
    L

    Somebody may be confused about the solution why we can use n%9 to represent the answer。
    We can start with the conclusion,which we may have learned at school:

    If number n is divisible by 3, the sum of all its digits also is divisible by 3.

    let's see how did this work:
    For number n, like the form of "ab",the value is n = 10a + b = 9a + (a + b),when n is divisible by 3,
    of course (a + b) is divisible by 3.For a number has more digits,it's the same situation:
    a(n)*10^(n)+a(n-1)10^(n-1)+.+a(1)10+a(0)
    =a(n)
    [10^(n)-1]+a(n-1)
    [10^(n-1)-1]+...+a(1)*9+[a(n)+a(n-1)+...+a(0)]

    From the proving process,we may think why don't try to divide by 9,since the number
    a(n)[10^(n)-1]+a(n-1)[10^(n-1)-1]+...+a(1)*9 is divisible by 9 . We can easily get a further conclusion:

    A number n and the sum of all its digits share the same remainder when divided by 9.

    That's the reason why does this work :

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

    Forgive my poor English.


Log in to reply
 

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