Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Java/String to integer/solution2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public int myAtoi(String s) {
s = s.trim();
if (s.isEmpty()) {
return 0;
}

int ans = 0, i = 0;
boolean neg = s.charAt(0) == '-';
boolean pos = s.charAt(0) == '+';

if (neg || pos) {
i++;
}

while (i < s.length() && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';

if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return neg ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}

ans = ans * 10 + digit;
i++;
}

return neg ? -ans : ans;
}
}