What's the complexity of the iterative solution?


  • 1
    H

    I know the best solution should be one line of code: return (num==0)? 0 : ((num - 1) % 9 + 1);

    but just curious, what's the complexity for the iterative solution as below?

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

    Thanks!


  • 0
    H
     while (num > 0) {
            num /= 10;
        }
    

    so that is the case , I'd like to say it's O(n) . n is num.length


  • 0
    S

    this seems wrong answer,when the test case is 18,your answer will be 1,not 9


  • 0
    F

    You can argue that its O(1) because an integer is never more than 32 bits.


Log in to reply
 

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