[LeetCode] String to Integer (atoi)

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.

解题思路:

本身没有什么难度,需要弄清楚题意。比如,输入的字符一定是正确的整数格式吗?会不会溢出,若溢出如何处理?若有数字字符其他的字符如何处理?在面试中,可以向面试官问清楚这些,便可以动手写代码哒。我们可以先用一个long long类型来存储中间结果。

class Solution {
public:
    int myAtoi(string str) {
        int len = str.length();
        if(len==0){
            return 0;
        }
        int sign=1;
        int startIndex=0;
        while(str[startIndex]==' '){
            startIndex++;
        }
        if(str[startIndex]=='-'){
            startIndex++;
            sign=-1;
        }else if(str[startIndex]=='+'){
            startIndex++;
            sign=1;
        }
        long long tempResult=0;
        for(int i=startIndex; i<len; i++){
            if(str[i]<'0'||str[i]>'9'){
                break;
            }
            tempResult *= 10;
            tempResult += str[i]-'0';
            if(tempResult>2147483647){
                break;
            }
        }
        tempResult *= sign;
        int result = (int)tempResult;
        if(result!=tempResult){
            if(sign<0){
                result=-2147483648;
            }else{
                result=2147483647;
            }
        }
        return result;
    }
};

二次刷题(2015-07-29)

class Solution {
public:
    int myAtoi(string str) {
        int len = str.length();
        if(len == 0){
            return 0;
        }
        int sign = 1;
        long long result = 0;
        int validIndex = 0;
        while(validIndex<len&&str[validIndex]==' '){
            validIndex++;
        }
        if(str[validIndex]=='+'){
            validIndex++;
        }else if(str[validIndex]=='-'){
            sign = -1;
            validIndex++;
        }
        while(str[validIndex]>='0'&&str[validIndex]<='9'){
            result *= 10;
            result += str[validIndex] - '0';
            long long temp = sign * result;
            if(temp >= INT_MAX){
                return INT_MAX;
            }
            if(temp <= INT_MIN){
                return INT_MIN;
            }
            validIndex++;
        }
        return int(sign*result);
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注