My minimalist c++ solutions, in two different ways.


  • 2
    E

    solution1: loop

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

    solution2: math

    class Solution {
    public:
        int addDigits(int num) {
            return (num - 1) % 9 + 1;
        }
    };

  • 0
    Y

    Wow can you please explain your second solution? Thank you.


Log in to reply
 

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