Share my 1-line solution


  • 2
    C

    We can find regular pattern by enumerate following case:
    1=1; 2=2; 3=3; 4=4; 5=5; 6=6; 7=7; 8=8; 9=9;
    10=1; 11=2; 12=3; 13=4; 14=5; 15=6; 16=7; 17=8; 18=9;
    19=1; 20=2; 21=3; 22=4; 23=5; 24=6; 25=7; 26=8; 27=9;
    ... ...
    so, we supposed that the rule is a cycle per 9 number.
    the math formulation:
    (num - 1) % 9 + 1

    note: num - 1 is to avoid k*9%9 = 0


  • 0
    C

    another solution by brute force:

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

  • 0
    B

    @casegame What about 811?


  • 0
    C

    @bradp7575 for 811, 8 + 1 + 1 = 10, 1+0=1.the answer is 1. In my solution, (811-1)%9+1 = 1.


  • 0

    seems doesn't work in Python since Python treat (0-1)%9 == 9


  • 0
    T

    Nice solution ! thanks


Log in to reply
 

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