Leetcode-8: String to Integer

  1. String to Integer (atoi)
    Medium
    3.7K
    11.3K
    Companies
    Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is ‘-’ or ‘+’. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. “123” -> 123, “0032” -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:

Only the space character ’ ’ is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example 1:

Input: s = “42”
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: “42” (no characters read because there is no leading whitespace)
^
Step 2: “42” (no characters read because there is neither a ‘-’ nor ‘+’)
^
Step 3: “42” (“42” is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:

Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" (‘-’ is read, so the result should be negative)
^
Step 3: " -42" (“42” is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:

Input: s = “4193 with words”
Output: 4193
Explanation:
Step 1: “4193 with words” (no characters read because there is no leading whitespace)
^
Step 2: “4193 with words” (no characters read because there is neither a ‘-’ nor ‘+’)
^
Step 3: “4193 with words” (“4193” is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.

Constraints:

0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ’ ', ‘+’, ‘-’, and ‘.’.

这道题的题目出的比较含糊,测试例子里面的情况都要特别注意。我的code写的太冗余,注释掉的code是Leetcode里面的,写的比较好。

#include <iostream>
#include <string>
#include <climits>

using namespace std;

int myAtoi(string str) {
    if (str.size()==0) return 0;   //empty string returns 0

    size_t flagPos=str.size();
    size_t startPos=str.size();
    for (auto i=0; i<str.size(); ++i) {
        if ((str.at(i)=='+' || str.at(i)=='-') && flagPos==str.size() )flagPos=i;

        if (isdigit(str.at(i))) {
            startPos=i;
            break;
        }
    }
    if (flagPos!=str.size() && (startPos-flagPos>1)) return 0;
    if (startPos==str.size()) return 0;   //invalid string returns 0
    else if (startPos>=1 && str.at(startPos-1)!='+' && str.at(startPos-1)!='-' && str.at(startPos-1)!=' ') return 0;

    bool positive=true;
    if ((startPos>0) && (str.at(startPos-1)=='-')) positive=false;
    if (positive && startPos>=2 && str.at(startPos-2)=='-') return 0;
    if (!positive && startPos>=2 && str.at(startPos-2)=='+') return 0;

    int result=positive? str.at(startPos)-'0' : '0' - str.at(startPos);
    for (auto i=startPos+1; i<str.size(); ++i) {
         if (isdigit(str.at(i))) {
            if (!positive) {
                if (result < INT_MIN / 10 || (result == INT_MIN / 10 && str.at(i) - '0' > 7))
                    return INT_MIN;
                else
                    result=result*10+'0'-str.at(i);
            }
            else {
                if (result >  INT_MAX / 10 || (result == INT_MAX / 10 && str.at(i) - '0' > 7))
                    return INT_MAX;
                else
                    result=result*10+str.at(i)-'0';
            }
         }
         else
            break;
    }

    return result;
}
#if 0
int myAtoi(string str) {
    int sign = 1, base = 0, i = 0;
    while (str[i] == ' ') { i++; }
    if (str[i] == '-' || str[i] == '+') {
        sign = 1 - 2 * (str[i++] == '-');
    }
    while (str[i] >= '0' && str[i] <= '9') {
        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
            if (sign == 1) return INT_MAX;
            else return INT_MIN;
        }
        base  = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
#endif // 0

int main()
{
    string s="123";
    cout<<myAtoi(s)<<endl;

    string s1="-23211";
    cout<<myAtoi(s1)<<endl;

    string s2="2147483647";
    cout<<myAtoi(s2)<<endl;

    string s3="-2147483648";
    cout<<myAtoi(s3)<<endl;

    string s4="000";
    cout<<myAtoi(s4)<<endl;

    string s5="+-2";
    cout<<myAtoi(s5)<<endl;

    string s6=" ++1""  -0012a42";
    cout<<myAtoi(s6)<<endl;

    string s7="2147483648";
    cout<<myAtoi(s7)<<endl;

    string s8="-2147483649";
    cout<<myAtoi(s8)<<endl;

    string s9="  +  413";
    cout<<myAtoi(s9)<<endl;

    string s10=" ++1";
    cout<<myAtoi(s10)<<endl;

    string s11=" b11228552307";
    cout<<myAtoi(s11)<<endl;

    string s12="    010";
    cout<<myAtoi(s12)<<endl;

    string s13="w10734368512";
    cout<<myAtoi(s13)<<endl;

    return 0;
}

二刷:

class Solution {
public:
    int myAtoi(string s) {
        long long res = 0;
        int len = s.size();
        int startPos = 0, endPos = 0;
#define UPP (long long)(pow(2, 31) - 1)
#define LPP (long long)(-pow(2, 31))
        while (startPos < len && s[startPos] == ' ') startPos++;
        if (startPos < len && 
            !isdigit(s[startPos]) && 
            s[startPos] != '+' && 
            s[startPos] != '-') return 0;
        if (s[startPos] == '+' || s[startPos] == '-') endPos = startPos + 1;
        else endPos = startPos;

        while (endPos < len && isdigit(s[endPos])) endPos++;
        string newS = s.substr(startPos, endPos - startPos);
        bool isNeg = (newS[0] == '-');
        if (newS[0] == '+' || newS[0] == '-') newS = newS.substr(1);
        int newLen = newS.size();
        for (int i = 0; i < newLen; i++) {
            res = res * 10 + (newS[i] - '0');
            if (res > UPP) return isNeg ? LPP : UPP;
        }
        return isNeg ? -res : res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值