LeetCode 8 — String to Integer (atoi)(C++ Java Python)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dragon_dream/article/details/19677643

题目:http://oj.leetcode.com/problems/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.

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.

题目翻译:

实现atoi,将字符串转换为整数。
提示:仔细考虑所有可能的输入情况。如果你想要挑战,请不要看下面,并问自己有哪些可能的输入情况。

注:这个问题有意模糊说明(即没有给定输入说明)。你负责预先收集所有的输入需求。

atoi的需求:
该函数首先丢弃尽可能多的空白(whitespace )字符直到遇到一个非空白字符。从这个字符开始,有一个可选的初始加号或减号,后面是尽可能多的数字,把它们当成数值解释。

该字符串在形成整数的字符后面可以包含额外字符,它们会被忽略,对这个函数的行为没有影响。

如果str中的第一个非空白字符序列不是一个有效的整数,或者如果这样的序列不存在(str是空的或只包含空白字符),不执行任何转换。

如果没有执行任何有效的转换,则返回0。如果正确的值超出了可表示的值的范围,返回INT_MAX(2147483647)或INT_MIN(-2147483648)。

分析:

        注意考虑特殊情况。

C++实现:

class Solution {
public:
    int atoi(const char *str) {
    	if(str == NULL)
    	{
    		return 0;
    	}

    	int i = 0;
    	while(str[i] == ' ')
		{
			++i;
		}

		int sign = 1;
		if(str[i] == '-')
		{
			sign = -1;
			++i;
		}
		else if(str[i] == '+')
		{
			++i;
		}

		long long res = 0;
    	while(str[i] != '\0')
    	{
    		if(str[i] >= '0' && str[i] <= '9')
    		{
    			res = res * 10 + (str[i] - '0');

    			if(res > INT_MAX)
    			{
    				return sign == -1 ? INT_MIN : INT_MAX;
    			}
    		}
    		else
    		{
    			break;
    		}

    		++i;
    	}

		return sign * res; 
    }
};

Java实现:

public class Solution {
    public int atoi(String str) {
		String s = str.trim();

		if (s.length() == 0) {
			return 0;
		}

		int INT_MAX = Integer.MAX_VALUE;
		int INT_MIN = Integer.MIN_VALUE;
		
		int sign = 1;
		int res = 0;
		
		int i = 0;
		if (s.charAt(0) == '-') {
			sign = -1;
			++i;
		} else if (s.charAt(0) == '+') {
			++i;
		}

		for (; i < s.length(); ++i) {
			char digit = s.charAt(i);
			if (digit >= '0' && digit <= '9') {
				if (res > INT_MAX / 10 || digit - '0' > INT_MAX - res * 10) {
					return sign == -1 ? INT_MIN : INT_MAX;
				}

				res = res * 10 + (digit - '0');
			} else {
				break;
			}
		}

		return sign * res;
    }
}

Python实现1:

class Solution:
    # @return an integer
    def atoi(self, str):
        s = str.strip()
        
        if len(s) == 0:
            return 0
        
        INT_MAX, INT_MIN = 2147483647, -2147483648
        
        sign = 1
        if s[0] in '+-': 
            if s[0] == '-':
                sign = -1
            s = s[1:]
            
        if s.isdigit(): 
            res = int(s)
        else:
            i = 0
            while s[i].isdigit():
                i += 1
            if i != 0:
                s = s[0:i]
                res = int(s)
            else:
                return 0

        if res > INT_MAX:
            return INT_MIN if sign == -1 else INT_MAX
        
        return sign * res

Python实现2:

<pre code_snippet_id="199947" snippet_file_name="blog_20140222_4_5943964" name="code" class="python">class Solution:
    # @return an integer
    def atoi(self, str):
        s = str.strip()
        
        if len(s) == 0:
            return 0
        
        INT_MAX, INT_MIN = 2147483647, -2147483648
    
        sign = 1
        i = 0        
        if s[0] == '-':
            sign = -1
            i += 1
        elif s[0] == '+':
            i += 1
            
        res = 0
        while i < len(s):
            digit = ord(s[i]) - ord('0')
            if digit >= 0 and digit <= 9:
                res = res * 10 + digit
                if res > INT_MAX:
                    return INT_MIN if sign == -1 else INT_MAX
            else:
                break;
            
            i += 1;
        
        return sign * res

        感谢阅读,欢迎评论!



                                    
展开阅读全文

没有更多推荐了,返回首页