1. 程式人生 > >LeetCode--String to Integer (atoi)

LeetCode--String to Integer (atoi)

String to Integer (atoi)

1 題目

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

2 分析

這題將string型別的字元轉變為int型別,其實轉換的過程不復雜,只是限制條件太多,需要自己找出那些轉換是合法的,有一下幾個部分需要注意的。

2.1 特殊的情況

        1. 形如--2之類的string是不合法的,不能做出轉換,返回0.

        2. 形如13+8之類的轉換是合法的,返回13.

        3. 形如-2-之類的轉換的合法的,返回-2.

注意上面的幾種情況,解出這道題目就不難了。

2.2資料的溢位

在這整個過程中,string轉化為int型別的資料可能會大於long long 型別,所以我們在sum迴圈相加的時候就應該開始做出判斷,否則到最後資料溢位。

3 原始碼

class Solution {
public:
	int getIndex(string str) {
		int index = -1;
		for(int i = 0; i < str.size(); i++) {
			if(str[i] != ' ') {
				index = i;
				break;
			}
		}
		return index;
	}
	int getLastIndex(int index, string str) {
		int lastIndex = str.size();
        int tag = 0;
		for(int i = index; i < str.size(); i++) {
			if((str[i] < '0'||str[i] > '9')&&!(str[i] == '-'||str[i] == '+')) {
				lastIndex = i;
				break;
			}
		}
        //cout << "lastIndex" << lastIndex << endl;
		return lastIndex;
	}
    int myAtoi(string str) {
        int index = getIndex(str);
        //cout << "index" << index << endl;
        int flag = 0;
        string target;
        if(index == -1||str[index] != '-'&&str[index] != '+'&&(str[index] < '0'||str[index] > '9')) {
        	return 0;
        } else {
        	int lastIndex = getLastIndex(index, str);
        	
        	if(str[index] == '-') {
        		flag = -1;
        		target = str.substr(index+1, lastIndex-index-1);
                
        	} else if(str[index] == '+') {
        		flag = 1;
        		target = str.substr(index+1, lastIndex-index-1);
        	} else {
        		target = str.substr(index, lastIndex-index);
        	}
            int tag = 0;
            for(int i = 0; i < target.size(); i++) {
                if(target[i] < '0'||target[i] > '9') {
                    lastIndex = i;
                    break;
                }
            }
            target = target.substr(0, lastIndex);
            //cout << target << endl;
        }

        long long sum = 0;
        for(int i = 0; i < target.size(); i++) {
            if(target[i] < '0'||target[i] > '9') {
                return 0;
            }
            sum = sum*10 + (target[i] - '0');
            if(sum > INT_MAX) {
                break;
            }
        }
        //cout << "flag" << flag << endl;
        if(flag == -1) {
        	sum = 0-sum;
        }
      	
        //cout << sum << endl;
        if(sum < INT_MIN) {
            return INT_MIN;
        } else if(sum > INT_MAX) {
            return INT_MAX;
        }else {
            return sum;
        }
    }
};