【leetcode刷题笔记】String to Integer (atoi)

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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


题解:思路很简单,就是要注意的细节很多:

  1. str中整数的前面可能有很多空格,要用str = str.trim(); 去掉,去掉之后还要判断str是否为空了,为空返回0;
  2. str中整数可能带有'+'或者'-',也可以不带,带有负号的时候要单独处理;
  3. str中整数后面可能还有乱七八槽的非数字符号,直接忽略,所以在遍历过程中如果遇到这些符号,说明整数部分遍历结束,要推出循环。
  4. str转换出来的整数有可能大于Integer.MAX_VALUE,此时需要返回Integer.MAX_VALUE;也有可能小于Integer.MIN_VALUE,此时需要返回Integer.MIN_VALUE。

代码如下:

 1 public class Solution {
 2     public int atoi(String str) {
 3         if(str == null || str.length() == 0)
 4             return 0;
 5         
 6         str = str.trim();
 7         if(str.length() == 0)
 8             return 0;
 9         
10         int kepeler = 0;
11         boolean isNeg = false;
12         if(str.charAt(kepeler) == '-'){
13             isNeg = true;
14             kepeler++;
15         }
16         else if(str.charAt(kepeler) == '+')
17             kepeler++;
18         
19         long answer = 0;
20         for(;kepeler < str.length();kepeler++){
21             if(str.charAt(kepeler) < '0' || str.charAt(kepeler) > '9')
22                 break;
23             answer = answer*10+str.charAt(kepeler) - '0';           
24         }
25         if(isNeg){
26             answer *= -1;
27             if(answer < Integer.MIN_VALUE)
28                 return Integer.MIN_VALUE;
29             return (int)answer;
30         }
31         else {
32             if(answer > Integer.MAX_VALUE)
33                 return Integer.MAX_VALUE;
34             return (int)answer;
35         }
36     }
37 }
原文地址:https://www.cnblogs.com/sunshineatnoon/p/3856426.html