Leetcode008. String to Integer (atoi)

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

 

转载于:https://www.cnblogs.com/zeroArn/p/5852698.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值