为什么要求解逆整数(Leet码)O((log10(n))?

问题描述 投票:0回答:2

有问题的problem要求反转32位带符号整数。这是Java中给定的解决方案:

    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

根据解决方案的解释,因为x中大约有log10(x)个数字,所以时间复杂度为O(log10(n))。直观上,while循环似乎有n-1次迭代,其中n是位数。 (即:7位数字需要进行6次迭代)。但是,该解决方案和给定的复杂度意味着n是整数本身,而不是位数。谁能帮助我直观地了解为什么上述解决方案是log10(n)?

java big-o logarithm
2个回答
0
投票

如果x是整数,则floor(log10(x))+1等于x中的位数。

让log(10)x =某个数字y。然后10 ^ y = x。例如,>

log(10) 10 = 1   
log(10) 100 = 2  
log(10) 1000 = 3 
...

让我知道这是否不能回答您的问题。


0
投票
Let's say the x = 123.

int rev = 0;

rev = rev * 10 + x % 10; // rev = 3,   1st iteration.

x = x/10;              // x = 12

rev = rev * 10 + x % 10;  // rev = 3 * 10 + 2 = 32,  2nd iteration

x = x/10;              // x = 1

rev = rev * 10 + x % 10;  // rev = 32 * 10 + 1 = 321, 3rd iteration.

x = 0 so the  loop terminates after 3 iterations for 3 digits.
© www.soinside.com 2019 - 2024. All rights reserved.