Open yokostan opened 5 years ago
class Solution { public int myAtoi(String str) { if (str.length() == 0) { return 0; } int index = 0; while (index < str.length() && str.charAt(index) == ' ') { index++; } int sign = 1; //1 for positive, -1 for negative if (index >= str.length()) { return 0; } if (str.charAt(index) != '-' && str.charAt(index) != '+'&& !Character.isDigit(str.charAt(index))) { return 0; } else if (str.charAt(index) == '-') { sign = -1; index++; } else if (str.charAt(index) == '+') { index++; } int res = 0; while (index < str.length()) { if (!Character.isDigit(str.charAt(index))) { break; } if(Integer.MAX_VALUE/10 < res || Integer.MAX_VALUE/10 == res && Integer.MAX_VALUE %10 < str.charAt(index) - '0') { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } res = res*10 + str.charAt(index) - '0'; index++; } return res*sign; } }
Dealing with EDGE cases. Good details to rememeber:
if (index >= str.length()) { return 0; }
to avoid " " case.
if(Integer.MAX_VALUE/10 < res || Integer.MAX_VALUE/10 == res && Integer.MAX_VALUE %10 < str.charAt(index) - '0') { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; }
Dealing with EDGE cases. Good details to rememeber:
to avoid " " case.