您的位置:首页 > 其它

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

2016-09-17 21:09 357 查看
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 spaces
str = str.trim();

char flag = '+';

// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;

// calculate value
while (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 min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;

return (int) result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: