[LeetCode Java] 8 String to Integer (atoi)

来源:互联网 发布:布拉莫斯导弹 知乎 编辑:程序博客网 时间:2024/05/15 00:01
/** *  * Implement atoi to convert a string to an integer. * 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. * */public class StringToInteger {static int atoi(String str) {String s = str.trim();int flag = 1;int result = 0;int index = 0;if (s.length() == 0) {return 0;}if (s.charAt(0) == '-') {flag = -1;index = 1;}if (s.charAt(0) == '+') {index = 1;}while(index < s.length()) {if (!isNumber(s.charAt(index))) {return result * flag;}int num = s.charAt(index) - '0';if (flag == 1) {if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && num >= Integer.MAX_VALUE % 10)) {return Integer.MAX_VALUE;}} else {if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && num >= Integer.MAX_VALUE % 10 + 1)) {return Integer.MIN_VALUE;}}result = result * 10 + num;index++;}return result * flag;}static boolean isNumber(char c) {if(c - '0' >= 0 && c - '0' <= 9) return true;return false;}public static void main(String[] args) {System.out.println(atoi("-1234"));System.out.println(atoi("1234"));System.out.println(atoi("+12345"));System.out.println(atoi("+-2"));System.out.println(atoi("+1d34"));System.out.println(atoi("    010"));System.out.println(atoi("  -0012a42"));}}

0 0