LeetCode 8 String to Integer (string转int)

本文详细解析了LeetCode上字符串转整数(Atoi)的问题,提供了完整的Java代码实现,并对输入的各种情况进行了全面考虑。

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

题目来源:https://leetcode.com/problems/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.

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.

 

解题思路:

照着要求写代码,可以总结如下:

1. 字串为空或者全是空格,返回0; 

2. 字串的前缀空格需要忽略掉;

3. 忽略掉前缀空格后,遇到的第一个字符,如果是‘+’或‘-’号,继续往后读;如果是数字,则开始处理数字;如果不是前面的2种,返回0;

4. 处理数字的过程中,如果之后的字符非数字,就停止转换,返回当前值;

5. 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值。

 

Java代码:

 1 public class Solution {
 2     public int myAtoi(String str) {
 3         int max = Integer.MAX_VALUE;
 4         int min = -Integer.MIN_VALUE;
 5         long result = 0;
 6         str = str.trim();
 7         int len = str.length();
 8         if (len < 1)
 9             return 0;
10         int start = 0;
11         boolean neg = false;
12  
13         if (str.charAt(start) == '-' || str.charAt(start) == '+') {
14             if (str.charAt(start) == '-')
15                 neg = true;
16             start++;
17         }
18  
19         for (int i = start; i < len; i++) {
20             char ch = str.charAt(i);
21  
22             if (ch < '0' || ch > '9')
23                 break;
24             result = 10 * result + (ch - '0');
25             if (!neg && result > max)
26                 return max;
27             if (neg && -result < min)
28                 return min;
29  
30         }
31         if (neg)
32             result = -result;
33  
34         return (int) result;
35     }
36  
37 };

 

转载于:https://www.cnblogs.com/zpfbuaa/p/5076830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值