8. String to Integer (atoi) Java Solutin

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

Show Tags
Show Similar Problems
 
题意: 

实现 atoi,将字符串转化为整数。


注意考虑所有可能的情况。



算法分析: 

1. 
先去掉多余的空格字符,从第一个非空格字符开始。


2. 
按顺序读数字,如果出现下面三种情况则结束:


2.1 
异常字符出现(异常字符跳过不计)。


2.2 
数字越界(返回最接近的整数)。


2.3 
字符串结束

 1 public class Solution {
 2     public int myAtoi(String str) {
 3         if(str == null) return 0;
 4         str = str.trim();
 5         if(str.length() == 0) return 0;
 6         Boolean isNex = false;
 7         int i = 0;
 8         if(str.charAt(0) == '+' || str.charAt(0) == '-'){
 9             i++;
10             if(str.charAt(0) == '-')
11                 isNex = true;
12         }
13         long result = 0;//若定义为int,边界值将会溢出。
14         for(;i<str.length();i++){
15             if(str.charAt(i) > '9' || str.charAt(i) < '0')
16                 break;
17             result = result*10 + str.charAt(i) - '0';
18             if(result > Integer.MAX_VALUE && !isNex)
19                 return Integer.MAX_VALUE;
20             if(-result < Integer.MIN_VALUE && isNex)
21                 return Integer.MIN_VALUE;
22         }
23         if(!isNex) return (int) result;
24         else result = -result;
25         return (int)result;
26     }
27 }
原文地址:https://www.cnblogs.com/guoguolan/p/5387048.html