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.
题意:将字符创转换为整数(int类型)
思路:
题目本身不难,但是需要考虑各种异常的输入,在leetcode的异常输入包括:
1. 输入为null或“”;
2. 判断“+,-“符号;
3. 错误字符;
4. 字符串中存在空格(开头的空格是可以跳过的,但是其他位置的空格当做异常字符对待);
5. int类型溢出(比较麻烦)
代码如下:
public int myAtoi(String str) { //处理输入为空的字符串 if(str == null || "".equals(str)) return 0; int start = 0; //跳过开头的空格 for(; start<str.length(); start++) if(str.charAt(start) != ‘ ‘) break; //处理“+”“-”符号,并用flag标记是正数还是负数 int flag = 1; if(str.charAt(start) == ‘+‘ || str.charAt(start) ==‘-‘) { if(str.charAt(start) == ‘-‘) flag = -1; start++; } else if(str.charAt(start) < ‘0‘ || str.charAt(start) > ‘9‘) { return 0; } int result = 0; for(;start < str.length();start++) { //处理异常字符(包括空格) if(str.charAt(start) < ‘0‘ || str.charAt(start) > ‘9‘) return result*flag; //处理溢出 if(result > Integer.MAX_VALUE / 10) return flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; result = result * 10; //处理加法溢出,注意下面的计算顺序,如果顺序错了也会溢出的 int curr = str.charAt(start)-‘0‘; if(Integer.MIN_VALUE+result+curr > 0) return (flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE); else if(result-Integer.MAX_VALUE+curr>0) return (flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE); else result = result + curr; } return result*flag; }
LeetCode-8 String to Integer (atoi)
原文:http://www.cnblogs.com/linxiong/p/4456807.html