8-String to Integer(atoi) C++

8-String to Integer(atoi) C++

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.

题意:非常好理解的一个题目,字符串转化成整形,要求从第一个不是空格的字符开始算,最长的连续的一串可以转化成int类型的子串,这个子串如果能转化成int类型可以表示的数字就返回该数字,如过不可以就返回0。比如:“     2132141dasfas123123”返回2132141,“dasas12412412”返回0,当然如果子串是以“-”“+”开头的话就要看后面的字符情况。

解析:首先从前到后的找到第一个不是空格的字符,然后再判断这个字符是不是“+”“-”号,最后在用一个循环来实现字符串和数字的转化,当然要判断一下是不是在int所能表示的范围内。

class Solution {
public:
    //AC - 8ms - using dumb direct method;
    int myAtoi(string str) 
    {
        int i = 0;
        int sign = 1;
        long num = 0;
        while(isspace(str[i])) i++;
        if(str[i]=='-' || str[i]=='+')
            if(str[i++] == '-') sign *= -1;
        while(str[i]=='0') i++;
        while(isdigit(str[i]))
        {
            num = 10*num + str[i++]-'0';
            if(num > fabs(long(INT_MIN))) break;
        }
        num *= sign;
        if(num < INT_MIN) return INT_MIN;
        if(num > INT_MAX) return INT_MAX;
        return num;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值