Leetcode : 8 String to Integer (atoi) C++

Description

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.

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.

分析

就是手动实现一遍string to int的函数,考虑各种情况:
从第一个非空字母开始考虑,跳过之前的空格
全为空格或者为空串 –> 0
第一个非空字母开始的序列不能构成合法的数字 –>0
考虑数字前的正负号
超过INT_MAX 或INT_MIN就各自返回这两个值
合法数字之后的其他字母不产生影响

可以提交后根据Leetcode上的wrong answer样例来逐步调整

代码

#include<limits>
#include<cctype>
class Solution {
public:
    int myAtoi(string str) {
      if (str == "")return 0;
    bool neg = false;//记录是否有负号
    int len = str.length();
    long long temp = 0;//防止运算过程越界
    int i = 0,n=0;
    for ( i = 0; i < len; i++)
        if (!isblank(str[i]))break;//i记录第一个非空位置
    for (n = 0; n < len; n++)
        if (isdigit(str[n]))break;//n记录第一个数字位置

    if (i >= len - 1 && (!isdigit(str[len - 1]))) return 0;//全是空格
    if ((n - i) > 1 || (n - i == 1 && str[n - 1] != '-' && str[n - 1] != '+'))return 0;//数字前面负号不合法
    if (n > 0 && str[n - 1] == '-')neg = true;
    for (n; n < len; n++)
    {
        if(isdigit( str[n]))temp = temp * 10 + (str[n] - '0');//计算
        else break;
        if (neg == true && -temp <=INT_MIN)return INT_MIN;//注意等号
        if (neg!=true&&temp >= INT_MAX)return INT_MAX;

    }
    int ans = (neg == true) ? -(int)temp : (int)temp;//添加上负号
    return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值