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

String to Integer (atoi) ***

时间:2015-06-23 17:24:03      阅读:103      评论: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.

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 };

 

String to Integer (atoi) ***

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4595470.html

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