Integer.parseInt() and Integer.toString() runtime

你。 提交于 2021-01-05 07:45:10

问题


Would the runtime of Integer.parseInt(String i) and Integer.toString(int i) both be O(n)?


回答1:


Yes both of them Integer.parseInt("1000") and Integer.toString(1000) have time complexity O(N)

  • The internal code of Integer.parseInt("1000") reads the the strings char by char and covert to decimal in while loop

  • The internal code of Integer.toString(1000) reads the integers and convert every digit to char and stores in byte[] buf then creates new string from the byte array

Here is the code of 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;



回答2:


Well, Thinking about it you can bypass the O(n) for Integer.toString(int i) by simply adding + ""

e.g

String x = 555 + "";


来源:https://stackoverflow.com/questions/61782618/integer-parseint-and-integer-tostring-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!