LeetCode----8. String to Integer (atoi)

来源:互联网 发布:淘宝甩手铺货 编辑:程序博客网 时间:2024/06/07 17:28

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

Subscribe to see which companies asked this question

Runtime Error Message:Line 9: java.lang.NumberFormatException: For input string: "+"
Last executed input:"+"
2.超出最大范围打印边界值,而非0;
3.存在空格
4.+ -开头的符号
public class Solution {
    public int myAtoi(String str) {
 try{
       if(str==null||str.length()==0){return 0;}
  str=str.trim();
  int m=Integer.parseInt(str); 
  if(Integer.parseInt(str)>Integer.MAX_VALUE){return  Integer.MAX_VALUE;}
  if(Integer.parseInt(str)<Integer.MIN_VALUE){return Integer.MIN_VALUE;}
  return m;
   }catch(Exception e){
 
   }
          return 0;   
             
}
}



Input:" -0012a42"
Output:0
Expected:-12
public int atoi(String str) {if (str == null || str.length() < 1)return 0; // trim white spacesstr = str.trim(); char flag = '+'; // check negative or positiveint i = 0;if (str.charAt(0) == '-') {flag = '-';i++;} else if (str.charAt(0) == '+') {i++;}// use double to store resultdouble result = 0; // calculate valuewhile (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {result = result * 10 + (str.charAt(i) - '0');i++;} if (flag == '-')result = -result; // handle max and minif (result > Integer.MAX_VALUE)return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE)return Integer.MIN_VALUE; return (int) result;}


0 0