LeetCode 8. 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.
题目大意
实现字符串转换成整数函数,需要考虑到所有特殊情况,保证函数的鲁棒性。
解题思路
这道题考察的是你的思维严谨性,建议先想清楚一系列完整的测试用例后再开始编写代码,需要处理以下四种特殊情况:
- 前置空白字符
- 符号位
- 溢出
- 无效输入
代码如下:
class Solution { public int myAtoi(String str) { if(str==null || str.length()==0) return 0; int sign = 1, base = 0, index = 0; // 处理前置空白字符 while(str.charAt(index)==' ' && index<str.length()) index++; // 处理符号位 if(str.charAt(index)=='+' || str.charAt(index)=='-'){ sign = str.charAt(index++)=='+'? 1: -1; } while(index<str.length() && str.charAt(index)>='0' && str.charAt(index)<='9'){ // 处理溢出 if(base > (Integer.MAX_VALUE / 10) || (base == (Integer.MAX_VALUE / 10) && (str.charAt(index)-'0') > 7)){ return sign == 1? Integer.MAX_VALUE: Integer.MIN_VALUE; } base = base*10 + (str.charAt(index++)-'0'); } return sign * base; } } 注意:即使字符串一开始是数字,但是后面有其他字符出现,那么输出有效的部分。例如:输入”123bc”,输出123。

浙公网安备 33010602011771号