码迷,mamicode.com
首页 > 其他好文 > 详细

String to Integer(atoi)

时间:2014-08-01 04:35:11      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   strong   io   for   

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.

 

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

 

分析: 非常重要且出名的题目. 有非常多的边界情况要考虑。根据上面的spoiler,已经基本可以将整个流程写出来,但是注意INT_MAX 和 INT_MIN不同,这就造成了当符号不同时,边界不同需要注意

给出代码:

 1 class Solution {
 2 public:
 3 int atoi(const char *str) {
 4     int num = 0;
 5     bool sign = false;
 6     const int n = strlen(str);
 7     int i = 0;
 8     while (str[i] ==   && i < n) i++;
 9     if (str[i] == +) i++;
10     else if (str[i] == -) {
11         sign = true;
12         i++;
13     }
14     for (; i < n; i++) {
15         int rec = str[i]-0;
16         if (str[i] < 0 || str[i] > 9)
17             break;
18         if (num > INT_MAX / 10)
19         {
20             return sign?INT_MIN:INT_MAX;
21         }
22         
23         if(num == INT_MAX / 10)
24         {
25             if(sign && rec>(INT_MAX%10+1)) return INT_MIN;
26             else if(!sign && rec>INT_MAX%10) return INT_MAX;
27         }
28         num = num * 10 + str[i] - 0;
29     }
30     if(sign) num = - num;
31     return num;
32 }
33 };

 

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

String to Integer(atoi)

标签:style   blog   http   color   os   strong   io   for   

原文地址:http://www.cnblogs.com/soyscut/p/3883824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!