LeetCode-8. 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.

题目:实现  atoi  将字符串转换为整数

提示:  仔细考虑所有可能的输入案例。如果你想要一个挑战,请不要在下面看到,问自己什么是可能的输入案例。

注意:  这个问题的目的是模糊地指定(即没有给定的输入规范)。您有责任收集所有的输入要求。

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values,INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

题目分析:

因为这个题目中没有明确给出字符串的内容,所以我们得想到所有的情况。

1、可能会出现空字符串;

2、可以会出现'+','-';

3、可能会存在溢出问题;

4、可能会存在一部分的空格,同时存在一部分有效数据;

所以我们的代码必须去解决这些问题:

1、如果为空,直接返回0;

2、定义一个sign去记录正负问题如果出现'+'让sign=1,若出现'-'则sign=-1;

3、存在溢出如果为负数则返回最整数的最小值,如果为正整数则返回可以表示的最大正整数;

4、遇到空格直接跳过;

代码:

   int myAtoi(string str) {
        if(str.size() == 0)  return 0;
        
        int sign = 1,num = 0,i=0;
       while(str[i] == ' ')
       {
           i++;
       }
        if(str[i] == '+' || str[i] == '-')
        {
            sign = 1 - 2*(str[i] == '-');
            i++;
        }
        while(str[i] <= '9' && str[i] >= '0')
        {
            if(num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i]-'0')>7))
            {
                if(sign == 1)  return INT_MAX ;
                else
                    return INT_MIN; 
            }
            num = num*10 +(str[i] - '0');
            i++;
        }
         return num*sign;  
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值