• [LeetCode] 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.

    spoilers alert... click to show requirements for atoi.

    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.

    Hide Tags
     Math String
     

    这题与Reverse Integer一样,题目本身不难,重点在于异常情况的判断。

    1.正负号;

    2.存在非法字符;

    3.越界。

    class Solution {
        public:
        int atoi(const char *str) {
                   // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (str == NULL) {
                return 0;
            }
            int head = 0;
            while (str[head] == ' ') {
                head++;
            }
            if (str[head] == '') {
                return 0;
            }
            
            int signal = 1;
            long long ans = 0;
            if (str[head] == '+' || str[head] == '-') {
                if (str[head++] == '-') {
                    signal = -1;
                }
            }
            
            while (str[head] >= '0' && str[head] <= '9') {
                ans = ans * 10 + str[head] - '0';
                if (ans * signal > INT_MAX) {
                    return INT_MAX;
                }
                if (ans * signal < INT_MIN) {
                    return INT_MIN;
                }
                head++;
            }
            return ans * signal;
        }
    };
  • 相关阅读:
    HDU 1556 差分,前缀和
    Full permutation
    PAT B1029
    字串简介
    阵列(3)
    完形填空
    关于c的比较
    19 阵列的复制
    switch述句
    阵列变数(2)
  • 原文地址:https://www.cnblogs.com/diegodu/p/4251566.html
Copyright © 2020-2023  润新知