Leetcode [8. String to Integer (atoi)]

Problem:8. String to Integer (atoi)

Question

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.

思路

考虑以下几种情况

纯数字类型
"012213" -> 12213

字符串有其他符号情况
"222.22" -> 222
"abcd222" -> 0
"22aba2323"-> 22

带有正负号情况
"+222.22" -> 222
"-22" -> -22

空格情况
"    1212" -> 1212
"  +12  123123" -> 12

操作流程
1. 首先除掉字符串前面的空格
2. 如果前面有正负号,优先处理好正负号
3. 截取前面的数字部分做转化(如果字符串最前面的子串是数字,截止到第一个非数字字符)
4. 考虑是否溢出

代码

class Solution {
public:
    int myAtoi(string str) {
        eraseEmptyCharater(str);
        int flag = 1;
        int overflow = false;
        if (str.size() !=0 && str[0] == '-')
            flag = -1;
        preprocess(str);
        if(str.size() == 0)
            return 0;
        int result = 0;
        int exp = str.size()-1;
        for(int i = 0; i < str.size(); i++) {
            if (unsigned(result) + unsigned((int(str[i])-48) * pow(10, exp)) > INT_MAX)
                overflow = true;
            result += (int(str[i])-48) * pow(10, exp);
            exp--;
        }
        if(overflow)
            return flag == 1 ? INT_MAX : INT_MIN;
        return result*flag;
    }

    void eraseEmptyCharater(string &str) {
        int i = 0;
        for (; i < str.size(); i++) {
            if (str[i] != ' ')
                break;
        }
        str = str.substr(i, str.size()-i);
    }

    void preprocess(string &str) {
        if(str[0] == '+' || str[0] == '-')
            str = str.substr(1, str.size()-1);
        string vocabulary = "0123456789";
        int lastDigPos = -1;
        for(int i = 0; i < str.size(); i++) {
            if (vocabulary.find(str[i]) != string::npos)
                lastDigPos++;
            else break;
        }
        str = str.substr(0, lastDigPos+1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值