首页 > 其他 > 详细

[Leetcode] String to Integer (atoi)

时间:2014-03-29 00:46:14      阅读:298      评论: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.

 

别人的代码,很精简,值得学习。

 

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int atoi(const char *str) {
 4         assert(str != NULL);  
 5         while(isspace(*str)) str++;  // remove ‘ ‘  
 6         
 7         int sign = (*str == -) ? -1 : 1;  
 8         if (*str == - || *str == +)    // if can check one char  
 9             str++;  
10                
11         int ret = 0;  
12         while(isdigit(*str))   // is digit  
13         {  
14             int digit = *str - 0;  
15                
16             if (INT_MAX / 10 >= ret)  
17                 ret *= 10;  
18             else  
19                 return sign == -1 ? INT_MIN : INT_MAX;  
20                    
21             if (INT_MAX - digit >= ret)  
22                 ret += digit;  
23             else  
24                 return sign == -1 ? INT_MIN : INT_MAX;  
25                    
26             str++;  
27         }  
28            
29         return ret * sign;  
30     }
31 };
bubuko.com,布布扣

[Leetcode] String to Integer (atoi),布布扣,bubuko.com

[Leetcode] String to Integer (atoi)

原文:http://www.cnblogs.com/easonliu/p/3631584.html

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