[LeetCode]String to Integer (atoi)
主要是一下步骤
1.delete space in front of str
2.check if str startsWith other characters
3.check if str is positive
4.check the end of str
5.check if overflow
public class Solution { public int myAtoi(String str) { while (str.length() > 0 && str.charAt(0) == ' ') { str = str.substring(1); } if (str.length() == 0 || (str.charAt(0) != '+' && str.charAt(0) != '-' && !isNum(str.charAt(0)))) { return 0; } int positive = 1; if (str.charAt(0) == '+') { str = str.substring(1); } else if (str.charAt(0) == '-') { positive = -1; str = str.substring(1); } boolean flg = true; int i = 0; for (; i < str.length(); i++) { if (!isNum(str.charAt(i))) { flg = false; break; } } if (!flg) { str = str.substring(0, i); } if (str.length() > 11) { return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (str.length() == 0) { return 0; } Long tmp = Long.valueOf(str); if (tmp > Integer.MAX_VALUE) { return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } return Integer.valueOf(str) * positive; } public boolean isNum(char c) { return c <= '9' && c >= '0'; } }