Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
publicclass{ publicintmyAtoi(String str){ char[] c = str.toCharArray(); int ans = 0; int flag = 1; int i = 0; if (c.length < 1) return0; while (c[i] == ' ' && i < str.length()) { i++; } if (c[i] == '+' || c[i] == '-') { flag = c[i] == '+' ? 1 : -1; i++; }
for (; i < str.length(); i++) { if (c[i] >= '0' && c[i] <= '9') { if (ans > Integer.MAX_VALUE / 10 || (Integer.MAX_VALUE / 10 == ans && Integer.MAX_VALUE % 10 < c[i] - '0')) { if (flag == 1) return Integer.MAX_VALUE; else { return Integer.MIN_VALUE; } } ans = ans * 10 + c[i] - '0'; } else { return flag * ans; } } return flag * ans; } }
近期评论