[LeetCode] 008. String to Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)

Github: https://github.com/illuz/leetcode


008.String_to_Integer (Easy)

链接

题目:https://oj.leetcode.com/problems/string-to-integer-atoi/

代码(github):https://github.com/illuz/leetcode

题意

将一个字符串转化为 int 型。

分析

注意如果超出范围就返回最接近的 int 数。

如:2147483648 大于 INT_MAX(2147483647) ,就返回 2147483647 。

之前可以用 sscanf 偷懒,最近更新了 case 就被卡了。

要注意几点:

  1. 跳过前面的空格,\t,\n
  2. 范围界定

使用 Python 的正则表达式可以很容易处理。

代码

C++:

class Solution {
public:
    int atoi(string str) {
		int ret = 0;
		bool overflow = false;
		int sign = 1;	// default is '+'
		int i = 0;
		int len = str.length();

		while (i < len && (str[i] == ' ' || str[i] == '\n' || str[i] == '\t'))
			++i;
		if (i == len)
			return 0;

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

		while (i < len) {
			if (!isdigit(str[i]))
				break;
			if ((sign == 1 && ret > (INT_MAX - (str[i]-'0')) / 10) ||
					(sign == -1 && -ret < (INT_MIN + (str[i]-'0')) / 10)) {
				overflow = true;
				break;
			}
			ret = ret * 10 + (str[i] - '0');
			++i;
		}
		if (overflow)
			ret = (sign == 1) ?  INT_MAX : INT_MIN;
		else
			ret *= sign;
		return ret;
    }
};

Java:

public class Solution {

    public int atoi(String str) {

        int ret = 0;
        boolean overflow = false;
        int sign = 1;	// default is '+'
        int i = 0;
        int len = str.length();

        while (i < len && (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t'))
            ++i;
        if (i == len)
            return 0;

        // get sign
        if (str.charAt(i) == '-') {
            ++i;
            sign = -1;
        } else if (str.charAt(i) == '+')
            ++i;

        while (i < len) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
                break;
            if ((sign == 1 && ret > (Integer.MAX_VALUE - (str.charAt(i)-'0')) / 10) ||
                    (sign == -1 && -ret < (Integer.MIN_VALUE + (str.charAt(i)-'0')) / 10)) {
                overflow = true;
                break;
            }
            ret = ret * 10 + (str.charAt(i) - '0');
            ++i;
        }
        if (overflow)
            ret = (sign == 1) ?  Integer.MAX_VALUE: Integer.MIN_VALUE;
        else
            ret *= sign;
        return ret;
    }
}

Python:

class Solution:
    # @return an integer
    def atoi(self, str):
        str = str.strip()
        if not str:
            return 0

        MAX_INT = 2147483647
        MIN_INT = -2147483648
        ret = 0
        overflow = False
        pos = 0
        sign = 1

        if str[pos] == '-':
            pos += 1
            sign = -1
        elif str[pos] == '+':
            pos += 1

        for i in range(pos, len(str)):
            if not str[i].isdigit():
                break
            ret = ret * 10 + int(str[i])
            if not MIN_INT <= sign * ret <= MAX_INT:
                overflow = True
                break

        if overflow:
            return MAX_INT if sign == 1 else MIN_INT
        else:
            return sign * ret

使用 Python 的正则表达式:

class Solution:
    # @return an integer
    def atoi(self, str):
        str = str.strip()
        str = re.match(r'^[+-]?\d+', str).group()
        MAX_INT = 2147483647
        MIN_INT = -2147483648

        try:
            ret = int(str)
            if ret > MAX_INT:
                return MAX_INT
            elif ret < MIN_INT:
                return MIN_INT
            else:
                return ret
        except:
            return 0
时间: 2024-10-01 06:01:10

[LeetCode] 008. String to Integer (Easy) (C++/Java/Python)的相关文章

[LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 013.Roman_to_Integer (Easy) 链接: 题目:https://oj.leetcode.com/problems/roman-to-integer/ 代码(github):https://github.com/illuz/leetcode 题意: 把罗马数转为十进制. 分析: 跟 012. I

LeetCode 008 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 b

[LeetCode] 007. Reverse Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 007.Reverse_Integer (Easy) 链接: 题目:https://oj.leetcode.com/problems/Reverse-Integer/ 代码(github):https://github.com/illuz/leetcode 题意: 反转一个数. 分析: 注意读入和返回的数都是 in

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 014.Longest_Common_Prefix (Easy) 链接: 题目:https://oj.leetcode.com/problems/longest-common-prefix/ 代码(github):https://github.com/illuz/leetcode 题意: 求多个字符串的最长公共前缀

LeetCode 13 Roman to Integer (C,C++,Java,Python)

Problem: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Solution: 时间复杂度O(n) 题目大意: 与12题相反,给一个罗马数字,要求转化为十进制数字 解题思路: Java源代码(用时749ms): public class Solution { public int romanToInt(String s) {

【LeetCode】008 String to Integer (atoi)

题目:LeetCode 008 String to Integer 题意:完成内置函数atoi的功能,将字符串转换成整数. 教训:一开始理所应当的随便一写,然后发现有很多的异常情况需要处理.然后按照C++ Reference中关于atoi的规定一条一条写,才AC.另外还有一个溢出的问题,一开始以为int会自动处理直接返回边界值,其实不是,如果溢出的话大于2147483647的数会给变成负数,因此要单独判断是否会大,但是设置成longlong 之后出现的问题是,还有可能会溢出longlong,所以

LeetCode:String to Integer (atoi)

1.题目名称 String to Integer (atoi) (字符串到数字的转换) 2.题目地址 https://leetcode.com/problems/string-to-integer-atoi/ 3.题目内容 英文:Implement atoi to convert a string to an integer. 中文:实现atoi函数,将输入的字符串(String类型)转换为整型数据(Integer类型) 提示:实现的atoi函数需要满足以下特征 忽略字符串第一个非空格字符前的所

Leetcode 数 String to Integer (atoi)

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie String to Integer (atoi) Total Accepted: 9862 Total Submissions: 67880 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge,

【LeetCode】- String to 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). Y