星空网 > 软件开发 > Java

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代码:

 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

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

国际包裹液体:https://www.goluckyvip.com/tag/102592.html
寄国际包裹有包装有什么要求:https://www.goluckyvip.com/tag/102593.html
ems国际包裹收费标准:https://www.goluckyvip.com/tag/102594.html
寄国外包裹怎么收费:https://www.goluckyvip.com/tag/102595.html
深圳欧洲小包:https://www.goluckyvip.com/tag/102596.html
寄国外哪个包裹便宜:https://www.goluckyvip.com/tag/102597.html
探讨内地人开设香港账户的可行性 :https://www.kjdsnews.com/a/1836442.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流