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

刷题63—字符串转换整数 (atoi) 100.字符串转换整数 (atoi) 题目链接 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/string-to-integer-atoi 题目描述 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: 如果第一个非空字符为正或者负... 阅读详情

题目: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
         
感谢阅读,欢迎评论! 

 

        
String to Integer (atoi) - 字符串转为整形,atoi 函数(Java String to Integer (atoi) Implement atoi to convert a string to an integer. 【函数说明】atoi() 函数会扫描 str 字符串,跳过前面的空白字符(例如空格,tab缩进等),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。 【... 阅读详情

相关推荐

python3-实现atoi()函数

0.摘要 本文介绍c语言中的atoi函数功能,并使用python3实现。   1.atoi()函数 atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数。 函数定义形式:int atoi(const char *nptr); 函数会扫描参数 nptr字符串,跳过前面的空白字符(例如空格,tab缩进),直到遇上数字或正负符号才开始做转换; 在遇到非数字或...

qq_17753903的博客 7744

LeetCodeString to Integer (atoi) 解题报告

这道题在LeetCode OJ上难道属于Easy,但是通过率却比较低,究其原因是需要考虑的情况比较低,很少有人一遍过吧。 【题目】 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge,

跳出温水的青蛙 1万+

leetcode——8. String to Integer (atoi) (java)

这道题其实就是将字符串转化为整型。这个题不算难,但是主要需要注意一些特殊条件以及边界判定。 1、要求如果转化整型溢出,则输出最大(2^32-1)或最小值(-2^32) 2、如果首字符不是正负号或数字,则输出1 3、开头不能连续是字符。比如“+-2”这个要输出为0 4、开头可以时连续的空格,字符串转换从非空格的第一个字符开始。如"     -42" 输出-42 首先这个int溢出问题,与第...

菜鸡程序员的进阶 443

【力扣Leetcode题解系列之0008String to Integer (atoi):字符串转换整数 (atoi) 解题攻略】

本文介绍了力扣第8题“字符串转换整数(atoi)”的解题方法。题目要求实现一个类似C/C++atoi的函数,将字符串转换为32位有符号整数。解题需处理以下关键点:去除前导空格、判断正负号、提取连续数字字符并进行边界检查。文章提供了Python正则表达式法和常规遍历法两种解法,并给出了PythonJava、C、C++四种语言的代码实现。正则表达式法简洁高效,而常规遍历法则更直观地展现了处理流程。两种方法都需要注意32位整数的溢出问题,当结果超出[-2^31, 2^31-1]范围时返回对应的边界值。

youngerwang的博客 889

LeetCode8. String to Integer (atoi) 字符串转换整数

作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法代码日期 题目地址:https://leetcode-cn.com/problems/string-to-integer-atoi/ 题目描述 Implement atoi which converts a string to an int...

负雪明烛 1421

LeetCode之(8)字符串转换整数 (atoi)String to Integeratoi)

@[toc](0008.字符串转换整数 (atoi)String to Integeratoi)) 题目描述 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。 该字符串在有效的整数部分之后也可能会存在多余

euy的博客 234

LeetcodeString to Integer (atoi)

LeetCode(二)String to Integer (atoi)

Wing_93的博客 305

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

Problem: 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 pos

算法之道 3184

leetcode8题——*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 inpu

buptlrw的专栏 862

LeetCode 刷题记录 8. String to Integer (atoi)

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

dldldl1994的博客 508

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

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

水果君の日常 2408

[LeetCode] 8.String to Integer (atoi)

题目网址:https://leetcode.com/problems/string-to-integer-atoi/ String to Integer (atoi) My Submissions Question  Solution  Total Accepted: 67273 Total Submissions: 524634 Di

我心中有猛虎 细嗅蔷薇 568

LeetCode 12 — Integer to Roman(C++ Java Python

题目:http://oj.leetcode.com/problems/integer-to-roman/ Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 题目翻译: 给定一个整数,将其转换成罗马数字。 输入在1到3

龙之梦 2587

字符串转换整数(atoi) java实现

题目描述 https://leetcode-cn.com/problems/string-to-integer-atoi 请你来实现一个atoi函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 ...

WukongGo的博客 561

8. String to Integer (atoi)

题目: Implementatoito 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...

weixin_30416871的博客 71

[LeetCode] 8. String to Integer (atoi) 字符串转为整数

Implementatoito 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 case...

weixin_30748995的博客 89
上一篇: LeetCode 7 — Reverse Integer(C++ Java Python)
下一篇: LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)
lilongmark
博客等级 码龄14年 117粉丝 75原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值