String to Integer (atoi)
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 Solution { public int atoi(String str) { if (str==null || str.length()==0) { return 0; } //正负号 true是正 false是负 boolean flag = true; int result = 0; str = str.trim(); if (str.charAt(0)=='-') { flag = false; str = str.substring(1, str.length()); } if (str.charAt(0)=='+') { str = str.substring(1, str.length()); } String newstr = new String(); for (int i=0;i<str.length();i++) { if (str.charAt(i)<'0'||str.charAt(i)>'9') { break; } newstr += String.valueOf(str.charAt(i)); } for (int i=0;i<newstr.length();i++) { char c = newstr.charAt(newstr.length()-1-i); if (result==0 && c=='0') { continue; } if (c<'0'||c>'9') { return result; } int temp = (int)Math.pow(10,i); //判断溢出 if (Integer.MAX_VALUE - (c-'0')*temp >= result ) { result += (c-'0')*temp; } else { return flag ? Integer.MAX_VALUE : Integer.MIN_VALUE; } } if (flag) { return result; } else { return 0-result; } } }