题目
题目很简单,就是写一个函数把string转换成int,但是通过率只有可怜的11%,难点是要考虑所有情况,特别是int溢出边界,反正我是写了2个小时还没解决,先放到这,有空接着搞,现在应该还有最后一个bug。
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
******************************************/