Leetcode-08 字符串转换整数

Leetcode-08 字符串转换整数

题目描述

请你来实现一个 atoi 函数,使其能将字符串转换成整数。

题目类别

字符串

具体实现

class Solution {
public:
    bool isDigt(char c){
        if( c == '\0') return false;
        return c >= '0' && c <= '9';

    } 
    int myAtoi(string str) {
        long long num = 0;
        bool minus = false;
        int index = 0;
        while(index < str.size() && str[index] ==' '){index++;}
        if(str[index] == '+' || str[index] == '-' || isDigt(str[index]) ){
            if(str[index] == '+') index++;
            else if(str[index] == '-') {
                index++;
                minus = true;
            }
            int flag = minus ? -1 : 1;
            while(isDigt(str[index])){
                num = num * 10 + flag * (str[index] - '0');
                if((!minus && num > INT_MAX) || (num < INT_MIN)){
                    return flag > 0 ? INT_MAX : INT_MIN;
                }
                index++;
            }
            
        }
        return num;
    }
};
发布了38 篇原创文章 · 获赞 6 · 访问量 8558

猜你喜欢

转载自blog.csdn.net/qq_36400206/article/details/104229831