Integer.parseInt()和Integer.toString()运行时。

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

Integer.parseInt(String i)和Integer.toString(int i)的运行时间是否都是O(n)?

java string integer tostring parseint
1个回答
2
投票

是的,它们都是 Integer.parseInt("1000")Integer.toString(1000) 有时间上的复杂性 O(N)

  • 内部守则 Integer.parseInt("1000") 在while循环中逐个读取字符串,并将其覆盖为十进制。

  • 内部守则 Integer.toString(1000) 读取整数,并将每一个数字转换为char值,并存储在这个函数中。byte[] buf 然后从字节数组中创建新的字符串

以下是代码 Integer.parseInt()

            int i = 0, len = s.length();
            int limit = -Integer.MAX_VALUE;
            // some checks
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result -= digit;
            }
            return negative ? result : -result;

0
投票

好吧,想一想,你可以绕过Integer.toString(int i)的O(n),只需在其中加入 + ""

例如

String x = 555 + "";
© www.soinside.com 2019 - 2024. All rights reserved.