简体   繁体   English

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

[英]Integer.parseInt() and Integer.toString() runtime

Would the runtime of Integer.parseInt(String i) and Integer.toString(int i) both be O(n)? Integer.parseInt(String i) 和 Integer.toString(int i) 的运行时间都是 O(n) 吗?

Yes both of them Integer.parseInt("1000") and Integer.toString(1000) have time complexity O(N)是的,他们俩Integer.parseInt("1000")Integer.toString(1000)的时间复杂度为O(N)

  • The internal code of Integer.parseInt("1000") reads the the strings char by char and covert to decimal in while loop Integer.parseInt("1000")的内部代码在while循环中逐字符读取字符串并转换为十进制

  • 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 Integer.toString(1000)的内部代码读取整数并将每个数字转换为字符并存储在byte[] buf然后从字节数组创建新字符串

Here is the code of Integer.parseInt() :这是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;

Well, Thinking about it you can bypass the O(n) for Integer.toString(int i) by simply adding + ""好吧,考虑一下,您可以通过简单地添加+ ""来绕过 Integer.toString(int i) 的 O(n)

eg例如

String x = 555 + "";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM