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.

spoilers alert... click to show requirements for atoi.


分析:好烦的一道题。自己写了好多次都没AC,果然群众的力量比较大。12ms
 1 class Solution {
 2 public:
 3     int myAtoi(string str) {
 4         long long result = 0;
 5         int sign = 1;
 6         int size = str.length();
 7         int index = 0;
 8         
 9         while(str[index] == ' ' && index < size) index++;
10         
11         if(str[index] == '+') index++;
12         else if(str[index] == '-'){
13             index++;
14             sign = -1;
15         }
16         
17         for(; index < size; index++){
18             if(str[index] < '0' || str[index] > '9') break;
19             
20             result = result * 10 + str[index] - '0';
21             if(result > INT_MAX) return sign == 1 ? INT_MAX : INT_MIN;
22         }
23         return (int) sign * result;
24     }
25 };

 

posted @ 2015-06-23 14:55  amazingzoe  阅读(118)  评论(0编辑  收藏  举报