LeetCode算法题目: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.


分析:

题目其实不难,不过需要注意下面几点:

  • 字符串前的空白
  • 字符串所表示数值的正负号
  • 结束条件,遇到非数字或者字符’\0’结束
  • 考虑溢出,与int值所能表示的最大(0x7fffffff)和最小值进行比较
  • 考虑异常输入情况下,用全局变量valid来标识,对于”+/-” “0” “+abc”需要进行区分
  • 还有就是测试过程中发现的对于“+-2”的处理是返回0;对于超出范围的数,如果是正数则将其置为(0x7fffffff), 如果为负数则将其置为(- 0x7fffffff – 1)。

代码:

class Solution {
public:
    int atoi(const char *str) {
        //正负数标识 
        bool flag = false;
        //作为负数是否小于0x80000000的标识 
        int tmin = 0;
        long long sum = 0;
        //判断字符串是否为空 
        if(str == NULL)
            return 0;
        //去除前置空格    
        while(*str == ' ')
            str++;  
        //判断数的符号,当时以为可以有多个符号取最后一个呢,后来发现只允许一个符号位 
        if(*str == '-'){
                flag = true;
                str++;
        }
        else if(*str == '+'){
            str++;
        }
        //判断数的合法性 
        if(*str < '0'|| *str >'9')
                return 0;
        //处理有效字符的值 
        while(*str>='0'&&*str<='9'){
            sum = sum * 10 + *str -'0' ;
            //判断是否超过了规定的范围 
            if( !flag && sum > (int)0x7FFFFFFF){
                sum = (int)0x7FFFFFFF;
                break;
            }else if( flag && sum > (int)0x7FFFFFFF){
                sum = (int)0x7FFFFFFF;
                tmin = 1;
                break;
            }
            str++;
        }
        //判断数的符号 
        if(flag&&tmin)
            sum = -sum-1;
        else if(flag&&!tmin)
            sum = -sum;
        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值