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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

问题分析

和leetcode007的题目用到的点基本相同,只是有些情况在运行测试后发现的,如“ +5df”这样的字符串是5,要考虑到,而不是返回错误,ok,直接上代码。

代码

class Solution {
public:
    int atoi(string str) {
        int i = 0;
        while (i < str.length() && str[i] == ' ')   { i++; }
        str = str.substr(i);
        if (str.length() <= 0) return 0;
        char arr[13];//选择13的目的是int型10进制最大值位数为10位,加上符号位为11位,防止溢出。
        int flag = 0;
        for (i = 0; i < 12 && i < str.length(); i++)
        {
            if (i == 0 && (str[i] == '-' || str[i] == '+') || str[i] >= '0' && str[i] <= '9')   arr[i] = str[i];
            else break;
        }
        arr[i] = '\0';
        int len = strlen(arr);
        if (!len || len == 1 && (arr[0] == '+' || arr[0] == '-')) return 0;
        long long k;
        sscanf(arr, "%lld", &k);
        if (k > INT_MAX) k = INT_MAX;
        if (k < INT_MIN) k = INT_MIN;
        return k;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值