MCPcopy Index your code
hub / github.com/Blankj/awesome-java-leetcode / myAtoi

Method myAtoi

src/com/blankj/medium/_0008/Solution.java:12–29  ·  view source on GitHub ↗
(String str)

Source from the content-addressed store, hash-verified

10 */
11public class Solution {
12 public int myAtoi(String str) {
13 int i = 0, ans = 0, sign = 1, len = str.length();
14 while (i < len && str.charAt(i) == ' ') ++i;
15 if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) {
16 sign = str.charAt(i++) == '+' ? 1 : -1;
17 }
18 for (; i < len; ++i) {
19 int tmp = str.charAt(i) - '0';
20 if (tmp < 0 || tmp > 9) break;
21 if (ans > Integer.MAX_VALUE / 10
22 || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) {
23 return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
24 } else {
25 ans = ans * 10 + tmp;
26 }
27 }
28 return sign * ans;
29 }
30
31 public static void main(String[] args) {
32 Solution solution = new Solution();

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected