leetcode 8 :String to Integer(atoi)

编程入门 行业动态 更新时间:2024-10-28 18:27:56

leetcode 8 :<a href=https://www.elefans.com/category/jswz/34/1769667.html style=String to Integer(atoi)"/>

leetcode 8 :String to Integer(atoi)

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

来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目解析
  • 思路一

使用正则表达式匹配出字符串中的数字,再利用解包的技巧,得到结果,最后再做溢出处理即可

import reclass Solution:def myAtoi(self, str: str) -> int:result = int(*re.findall(r'^[+-]?\d+', str.strip()))if result < -2 ** 31:return -2 ** 31elif result > 2 ** 31 - 1:return 2 ** 31 - 1return result     

更多推荐

leetcode 8 :String to Integer(atoi)

本文发布于:2023-07-28 15:43:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:String   leetcode   atoi   Integer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!