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

Leetcode008. String to Integer (atoi)

时间:2016-09-08 14:35:23      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

 1 /* improvement on dealing  with overflow accroding to this:
 2  * https://discuss.leetcode.com/topic/57452/c-solution-beats-100
 3  * 
 4  * be careful about the INT_MAX and INT_MIN 
 5  * this atoi is not thinking about special char like dot and so on.
 6  */
 7 
 8 class Solution {
 9 public:
10     int myAtoi(string str) {
11        int i,nega_sign=1;
12        long long int re=0;  //long long re to avoid overflow 
13        for(i=0;i<str.size();i++)       //skip to all the blank in the front of the string
14        {
15            if(str[i]!= )break;
16        }
17        if(str[i]==+)i++;             // deal with signature
18        else if(str[i]==-){ nega_sign=-1;i++;}
19        while(i<str.size()&&isdigit(str[i]))  
20 /*when the string is over or the current char is not a valid integral number,no more conversion will be performed.
21 */
22        {
23                re=re*10+str[i]-0;
24                if(nega_sign==-1&& -1*re<=INT_MIN)return INT_MIN;      //overflow
25                else if (nega_sign==1&&re>=INT_MAX)return INT_MAX;
26                i++;
27        }
28        return re*nega_sign;
29     }
30 };

 

Leetcode008. String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/zeroArn/p/5852698.html

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