zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    第十二周作业
    第11周学习总结
    第十周学习总结(五一作业)
    第九周作业
    第八周作业
    第七周作业
    PAT1049、1048、1047
    例题3-5,例题4-2,例题4-3
    PAT甲级真题打卡:1002. A+B for Polynomials
    PAT甲级真题打卡:1001.A+B Format
  • 原文地址:https://www.cnblogs.com/diegodu/p/4251566.html
Copyright © 2011-2022 走看看