且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode]8. String to Integer (atoi)

更新时间:2022-01-26 22:00:00

【题目】

点击打开链接

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.

【题意】

实现atoi函数功能,将字符串转换为整数。

【分析】

细节题:

要仔细考虑不同的测试用例:

1.     -3445  -> -345

2.    -34hhf67 -> -34

3.    +56 -> 56

4.   ++1 ->  0

5.   ++a -> 0

6.  溢出数据: -2147483649 -> -2147483648

2147483649  -> -2147483647

【代码】

/*********************************
*   日期:2014-02-05
*   作者:SJF0115
*   题号: String to Integer (atoi)
*   来源:http://oj.leetcode.com/problems/string-to-integer-atoi/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <limits.h>
using namespace std;


class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        long long result = 0;
        int flag = 1;
        int index = 0;
        //过滤空格
        while(str[index] == ' '){
            index++;
        }
        //判断是否有正负号
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            result = result * 10 + (str[i] - '0');
            if(flag == 1 && result > INT_MAX){
                return INT_MAX;
            }
            else if(flag == -1 && -1*result < INT_MIN){
                return INT_MIN;
            }
        }
        return (int)flag * result;
    }
};

int main() {
    Solution solution;
    char *str = "2147483649";
    int result = solution.atoi(str);
    cout<<result<<endl;
    return 0;
}

【代码2】

class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        int result = 0;
        int flag = 1;
        int index = 0;
        //过滤空格
        while(str[index] == ' '){
            index++;
        }
        //判断是否有正负号
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            //判断是否溢出
            if(result > INT_MAX / 10 || (result == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)){
                return flag == -1?INT_MIN:INT_MAX;
            }
            result = result * 10 + (str[i] - '0');
        }
        return flag * result;
    }
};

【温故】

/*---------------------------------------
*   日期:2015-05-07
*   作者:SJF0115
*   题目: 8.String to Integer (atoi)
*   网址:https://leetcode.com/problems/string-to-integer-atoi/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        int size = str.size();
        if(size == 0){
            return 0;
        }//if
        int index = 0;
        // 空格
        while(index < size && str[index] == ' '){
            ++index;
        }//while
        if(index >= size){
            return 0;
        }//if
        // 正负性
        int positive = 1;
        if(str[index] == '-'){
            positive = -1;
            ++index;
        }//if
        else if(str[index] == '+'){
            positive = 1;
            ++index;
        }//else
        long long result = 0;
        for(int i = index;i < size;++i){
            // 无效字符
            if(!isValid(str[i])){
                break;
            }//if
            result = result * 10 + (str[i] - '0');
            // 正数溢出
            if(positive == 1 && result > INT_MAX){
                return  INT_MAX;
            }//if
            // 负数溢出
            if(positive == -1 && -1*result < INT_MIN){
                return  INT_MIN;
            }//if

        }//for
        return positive*(int)result;
    }
private:
    bool isValid(char c){
        if(c >= '0' && c <= '9'){
            return true;
        }//if
        return false;
    }
};

int main() {
    Solution solution;
    string str("  -0012a42");
    cout<<solution.myAtoi(str)<<endl;
}

[LeetCode]8. String to Integer (atoi)