leetcode第八题 String to Integer (atoi) (java)
String to Integer (atoi)
String to Integer (atoi)
public class Solution { public int atoi(String str) { int length=str.length(); long result=0; int flag=1; Boolean bFlag=false,bSpace=false,bNum=false; if(length<=0) return (int) result; else{ char[] s=str.toCharArray(); for(int index=0;index<length;index++){ if(s[index]==32){ if(!bSpace) bSpace=true; if(bSpace&&bNum) return (int) ((int)flag*result); }else if(s[index]==43||s[index]==45){ if(!bFlag){ flag=-flag*(s[index]-44); bFlag=true; bNum=true; }else{ return (int) (flag*result); } }else if(s[index]<48||s[index]>57){ //0-9 ASCII:48-57 +:43 -:45 space:32 //System.out.println("Invalid Input!"); return (int) (flag*result); }else{ bNum=true; result=result*10+(s[index]-48); } if (flag*result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (flag*result < Integer.MIN_VALUE) return Integer.MIN_VALUE; } } return (int) (flag*result); } }