题目来源: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 };
原标题:LeetCode 8 String to Integer (string转int)
关键词:string