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) { String num_str=""; char[] str_char=str.toCharArray(); char[] sympo="-+".toCharArray(); boolean abs=true; for(int i=0;i<str.length();i++){ if(str_char[i]==sympo[0] ||str_char[i]==sympo[1]){ if(!Character.isDigit(str_char[i+1])){ return 0; } if(str_char[i]==sympo[0]){ abs=false; } } if(Character.isDigit(str_char[i])){ num_str+=String.valueOf(str_char[i]); } else{ if(num_str.length()!=0){ break; } } // if(Character.isDigit(str_char[i])){ // num_str+=String.valueOf(str_char[i]); // } if(num_str!=""){ if(Math.abs(Integer.parseInt(num_str))>=Integer.MAX_VALUE / 10){ return Integer.MAX_VALUE; } } } if(num_str!=""){ if(abs){ return Integer.parseInt(num_str); } else{ return -Integer.parseInt(num_str); } } else{ return 0; } } }
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
【LeetCode从零单排】No.8 String to Integer (丧心病狂的一道题)
原文地址:http://blog.csdn.net/buptgshengod/article/details/43602071