Leetcode008-String to Integer (atoi)

Leetcode008-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.

       尝试着自己去写,不看提示,发现还是有很多疏漏的地方,基本是靠着测试样例写通过了。总结起来基本可以分为:字符串处理问题、整数溢出问题、正负性问题。

AC版本

#include <limits>
#include <limits.h>

class Solution {
public:
    int myAtoi(string str) {
        int n = str.size();
        if(!n)
            return 0;
        bool ispositive = true;
        bool valid = true;
        int res = 0;
        // 删去开头空格
        while(str[0] == ' '){
            str.erase(0, 1);
            n--;
        }
        // 判断正负
        if(str[0] == '+' || str[0] == '-'){
            if(n == 1)
                return 0;
            else if(str[0] == '-')
                ispositive = false;
            str.erase(0, 1);
            n--;
        }
        for(int i=0; i<n; i++){
            // 出现非数字字符
            if(str[i]<'0' || str[i]>'9')
                break;
            int x = (int)(str[i]-'0');
            // 判断是否溢出
            if(numeric_limits<int>::max() / 10 >= res)
                res = res * 10;
            else{
                valid = false;
                break;
            }
            if(numeric_limits<int>::max() - x % 10 >= res)
                res = res + x % 10;
            else{
                valid = false;
                break;
            }
        }
        if(ispositive && valid)
            return res;
        else if(!ispositive && valid)
            return -res;
        else if(ispositive && !valid)
            return INT_MAX;
        else if(!ispositive && !valid)
            return INT_MIN;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值