LeetCode 8 String to Integer (string转int)

时间:2023-03-10 08:48:55
LeetCode 8 String to Integer (string转int)

题目来源: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代码:

 public class Solution {
public int myAtoi(String str) {
int max = Integer.MAX_VALUE;
int min = -Integer.MIN_VALUE;
long result = 0;
str = str.trim();
int len = str.length();
if (len < 1)
return 0;
int start = 0;
boolean neg = false; if (str.charAt(start) == '-' || str.charAt(start) == '+') {
if (str.charAt(start) == '-')
neg = true;
start++;
} for (int i = start; i < len; i++) {
char ch = str.charAt(i); if (ch < '0' || ch > '9')
break;
result = 10 * result + (ch - '0');
if (!neg && result > max)
return max;
if (neg && -result < min)
return min; }
if (neg)
result = -result; return (int) result;
} };