• 8. 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.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

    ===============

    string变int,字符串转化为int

    关键的地方是:

    1,什么合法的数字字符串

    2,字符串开头可以有空白符

    3,字符串第一个字符可以是+,-,也可以没有正负号

    4,整数溢出的处理方法?

      只比较n和MAX_INT/10的大小,

      即,若n>MAX_INT/10时,说明最后一步转换时,n*10一定大于MAX_INT,所以当得知n>MAX_INT/10,直接return MAX_INT

      若n==MAX_INT/10,那么比较最后一个数字c与MAX_INT%10的大小,如果n==MAX_INT/10 && c>MAX_INT%10,return MAX_INT

    代码实现:

    class Solution {
    public:
        int myAtoi(string str) {
            int num = 0;
            int sign = 1;
            const int n = str.length();
            int i = 0;
            while(i<n && str[i]==' ') i++;
    
            if(str[i] == '+'){
                i++;
            }else if(str[i]=='-'){
                sign = -1;
                i++;
            }
            for(;i<n;i++){
                if(!isdigit(str[i])) break;
                if(num > INT_MAX/10 ||
                    (num==INT_MAX/10 && (str[i]-'0')>INT_MAX%10)){
                    return sign==-1? INT_MIN:INT_MAX;
                }
                num = num*10+str[i]-'0';
            }
            return num*sign;
        }
    };
  • 相关阅读:
    算法导论之贪心算法
    编程过程中遇到的一些细节
    c++11和c99
    面试总结(YY一面)
    python(17):字典
    python(16):元组
    python(15):练习题
    python(14):列表
    python(13):字符串
    python(12):练习题
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5608107.html
Copyright © 2020-2023  润新知