LeetCode: String to Integer (atoi) 解题报告

本文详细解析了如何实现将字符串转换为整数的atoi算法,包括去除前后空格、处理正负号及数字字符转换。讨论了边界情况如非法字符、空字符串及越界处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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

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.

Solution

1. 用String s = str.trim();裁掉前面后面的空格。

2. 记录起始的+,-符号。

3. 用Long来转数字,这样的话就算越界也没什么了。

 1 public class Solution {
 2     public int atoi(String str) {
 3         if (str == null) {
 4             return 0;
 5         }
 6         
 7         // remove the spaces in the begining and the end.
 8         String s = str.trim();
 9         
10         boolean minus = false;
11         long num = 0;
12         for (int i = 0; i < s.length(); i++) {
13             /*
14              takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them              as a numerical value.
15             */
16             if (i == 0 && s.charAt(i) == '+') {
17                 continue;
18             } else if (i == 0 && s.charAt(i) == '-'){
19                 // get the 
20                 minus = true;
21                 continue;
22             }
23             
24             int c = s.charAt(i) - '0';
25             if (c > 9 || c < 0) {
26                 // invalid character.
27                 break;
28             }
29             
30             num = num * 10 + c;
31         }
32         
33         // If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is           // returned.
34         if (minus) {
35             num = -num;
36             num = Math.max(num, Integer.MIN_VALUE);
37         } else {
38             num = Math.min(num, Integer.MAX_VALUE);
39         }
40         
41         return (int)num;
42     }
43 }
View Code

2015.1.3 redo,

leetcode升级了test case,加入了更大的比long还大的数。这样我们必须在循环里就判断是不是越界就退出了,否则long也会爆掉的。

 1 public class Solution {
 2     public int atoi(String str) {
 3         long ret = 0;
 4         
 5         // ___+1234__
 6         // Delete the leading and tailing spaces.
 7         String sNew = str.trim();
 8         
 9         if (sNew.length() == 0) {
10             return 0;
11         }
12         
13         boolean positive = true;
14         for (int i = 0; i < sNew.length(); i++) {
15             char c = sNew.charAt(i);
16             if (i == 0 && c == '+') {
17                 continue;
18             } else if (i == 0 && c == '-') {
19                 positive = false;
20                 continue;
21             }
22             
23             if (!(c <= '9' && c >= '0')) {
24                 break;
25             }
26             
27             int dig = positive ? c - '0': '0' - c;
28             
29             ret = ret * 10 + dig;
30             
31             // bug 2: should consider the out of range.
32             if (ret > Integer.MAX_VALUE) {
33                 return Integer.MAX_VALUE;
34             } else if (ret < Integer.MIN_VALUE) {
35                 return Integer.MIN_VALUE;
36             }
37         }
38         
39         return (int)ret;
40     }
41 }
View Code

 

GitHub

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/Atoi.java

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值