# leetcode 8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

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.

public class A8StringtoInteger_atoi {

public int myAtoi(String str) {
if(str == null || "".equals(str = str.trim()))
return 0;
int sign = 1, i = 0;
long ans = 0L;
if(str.charAt(0) == '-') {
i++;
sign = -1;
} else if (str.charAt(0) == '+') {
i++;
}
for(; i < str.length(); i++) {
if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
ans = ans * 10L + (str.charAt(i) - '0');
if(ans * sign >= (long)Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if(ans * sign <= (long)Integer.MIN_VALUE)
return Integer.MIN_VALUE;
} else
break;
}
return (int)ans * sign;
}
}

• 本文已收录于以下专栏：

## [JAVA]LeetCode8 String to Integer (atoi)

Implement atoi to convert a string to an integer.
• fumier
• 2015年04月15日 16:09
• 954

## LeetCode题解--8. String to Integer (atoi)

• gatieme
• 2016年04月02日 23:10
• 1214

## [LeetCode][8]String to Integer (atoi)解析与模仿Java源码实现 -Java实现

Q： Implement atoi to convert a string to an integer. Hint: Carefully consider all possible i...
• u014629433
• 2016年06月07日 12:19
• 1215

## 【LeetCode】String to Integer (atoi) 解题报告

• ljiabin
• 2014年10月27日 16:19
• 12077

## LeetCode（8）String to Integer (atoi)

• fly_yr
• 2015年04月27日 16:57
• 3642

## Leetcode-8-String to Integer(atoi) C++

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases...
• u014056175
• 2016年06月27日 14:24
• 366

## LeetCode 8 String to Integer (atoi) (C,C++,Java,Python)

Problem: Implement atoi to convert a string to an integer. Hint: Carefully consider all poss...
• runningtortoises
• 2015年05月07日 10:38
• 2075

## leetcode: 8. String to Integer (atoi)

• isomebody
• 2017年07月04日 21:55
• 116

## LeetCode之8----String to Integer (atoi)

• Jung_zhang
• 2016年04月05日 19:53
• 424

## LeetCode 8. String to Integer (atoi)(字符串)

LeetCode 8. String to Integer (atoi)(字符串)
• jjhfen00
• 2017年06月07日 02:31
• 216

举报原因： 您举报文章：leetcode 8. String to Integer (atoi) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)