Integer.parseInt() and Integer.toString() runtime
Asked Answered
P

1

2

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

Prodigious answered 13/5, 2020 at 18:53 Comment(0)
M
3

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;
Marler answered 13/5, 2020 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.