首页 > 其他 > 详细

[LeetCode]String to Integer (atoi)

时间:2015-12-19 16:20:38      阅读:237      评论:0      收藏:0      [点我收藏+]

题目描述:(链接)

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.

解题思路:

题目挺麻烦的,需要考虑很多情况。

 1 class Solution {
 2 public:
 3     int myAtoi(string str) {
 4         int len = str.size();
 5         if(len == 0) return 0;
 6         
 7         int sign = 1;
 8         int i = 0;
 9         
10         while (str[i] ==  ) {  
11             i++;  
12         }
13         
14         // 符号
15         if(str[i] == + || str[i] == -) {
16             if(str[i] == +) {
17                 sign = 1;
18             } else {
19                 sign = -1;
20             }
21             ++i;
22         } 
23         
24         long ans = 0;
25         while(isdigit(str[i])) {
26             ans = ans * 10 + str[i] -0;
27             if(ans > INT_MAX) {
28                 return sign == 1 ? INT_MAX : INT_MIN;
29             }
30             ++i;
31         }
32         
33         return ans * sign;
34     }
35 };

 

[LeetCode]String to Integer (atoi)

原文:http://www.cnblogs.com/skycore/p/5059180.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!