作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
公众号:负雪明烛
本文关键词:字符串转整数,atoi,题解,Leetcode, 力扣,Python, C++, Java


题目地址:https://leetcode-cn.com/problems/string-to-integer-atoi/

题目描述

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is ‘-’ or ‘+’. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. “123” -> 123, “0032” -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  6. Return the integer as the final result.

Note:

  1. Only the space character ' ' is considered as whitespace character.
  2. 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.

题目大意

请你来实现一个 atoi 函数,使其能将字符串转换成整数。

首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:

  1. 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
  2. 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
  3. 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。

解题方法

这个题是我一直“珍藏”没做的题,因为我知道这个题的坑比较多。这次算是认真的做了一次。

重点还是理解题目给了什么规则:去除起始的空格;判断正负号;找第一个开始的数字开始,到第一个非数字字符处停止。

在这种字符串处理的题目中,我一般都是选用Python大法结合正则表达式,特别是正则表达式是大杀器。

做法:

  1. 去除开始和结尾的所有空字符,使用.strip()方法
  2. 使用正则表达式找出"+", "-", 数字 开始,到第一个非数字字符处停止的数字。该正则是 "^[+-]?\d+",可以用 http://tool.chinaz.com/regex/ 进行校验。
  3. 把数字转成整数(使用Python的int()函数,Python的int可以表示出无限大的数字,不用担心越界)。
  4. 如果超出了题目说的INT_MAXINT_MIN的边界,则返回INT_MAXINT_MIN

代码

Python代码如下。

import re
class Solution(object):
def myAtoi(self, num):
"""
:type str: str
:rtype: int
"""
num = num.strip()
if not num:
return 0
res = re.findall(r"^[+-]?\d+", num)
if not res:
return 0
res = int(res[0])
return max(min(res, 2 ** 31 - 1), -2 ** 31)

欢迎关注负雪明烛的刷题博客,leetcode刷题800多,每道都讲解了详细写法!

日期

2020 年 4 月 3 日 —— 这几天怎么啥都不想干

【LeetCode】8. String to Integer (atoi) 字符串转换整数的更多相关文章

  1. 【LeetCode】String to Integer (atoi)(字符串转换整数 (atoi))

    这道题是LeetCode里的第8道题. 题目要求: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止. 当我们 ...

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

    Implement atoi which converts a string to an integer. The function first discards as many whitespace ...

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

    Implement atoi which converts a string to an integer. The function first discards as many whitespace ...

  4. [Leetcode] String to integer atoi 字符串转换成整数

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

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

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  6. 【LeetCode】8. String to Integer (atoi) 字符串转整数

    题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...

  7. Leetcode8.String to Integer (atoi)字符串转整数(atoi)

    实现 atoi,将字符串转为整数. 该函数首先根据需要丢弃任意多的空格字符,直到找到第一个非空格字符为止.如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字 ...

  8. 【LeetCode每天一题】String to Integer (atoi)(字符串转换成数字)

    Implement atoi which converts a string to an integer.The function first discards as many whitespace ...

  9. Leetcode 8 String to Integer (atoi) 字符串处理

    题意:将字符串转化成数字. 前置有空格,同时有正负号,数字有可能会溢出,这里用long long解决(leetcode用的是g++编译器),这题还是很有难度的. class Solution { pu ...

随机推荐

  1. Linux软件安装管理:rpm与yum

    目录 1. rpm包的管理 1.1 介绍 1.2 rpm包的简单查询指令 1.3 rpm 包名的基本格式 1.4 rpm其它指令 1.5 卸载rpm包 1.6 安装rpm包 2. yum 2.1 说明 ...

  2. CAS简介

    概念 CAS(Compare And Swap 比较并交换),是 乐观锁 的一种典型实现机制. 乐观锁主要的两个步骤:冲突检测.数据更新. 当多个线程尝试使用CAS同时更新通过一个变量的时候,只有一个 ...

  3. 日常Java 2021/10/6

    声明自定义异常 class zidingyiException extends Exception{}//定义自己的异常类 单继承 public class A  {} public class B ...

  4. day06 HTTP协议

    day06 HTTP协议 HTTP协议 什么是http? HTTP 全称:Hyper Text Transfer Protocol 中文名:超文本传输协议 是一种按照URL指示,将超文本文档从一台主机 ...

  5. openwrt编译ipk包提示缺少feeds.mk文件

    问题具体表现如下 这个问题困扰了我两个多星期,总算解决了.解决方案如下: 首先,先应该把配置菜单调好. 我的硬件是7620a,要编译的ipk包为helloworld,所以应该使用 make menuc ...

  6. 【Linux】【Services】【nfs】nfs安装与配置

    1. 概念 1.1. NFS:Network File System,传统意义上,文件系统在内核中实现. 1.2. RPC:Remote Procedure Call protocol,远程过程调用, ...

  7. BigDecimal中要注意的一些事

    一.关于public BigDecimal(double val) BigDecimal中三个主要的构造函数 1 public BigDecimal(double val) 将double表示形式转换 ...

  8. 微服务下前后端分离的统一认证授权服务,基于Spring Security OAuth2 + Spring Cloud Gateway实现单点登录

    1.  整体架构 在这种结构中,网关就是一个资源服务器,它负责统一授权(鉴权).路由转发.保护下游微服务. 后端微服务应用完全不用考虑权限问题,也不需要引入spring security依赖,就正常的 ...

  9. 使用 OPC Browser 加载 OPC Server 监测点

    1,首先第一步,要连接OPC ,创建好 OPC对象. /// <summary> /// 连接OPC /// </summary> private string OPCIP=1 ...

  10. ABP VNext框架基础知识介绍(1)--框架基础类继承关系

    在我较早的时候,就开始研究和介绍ABP框架,ABP框架相对一些其他的框架,它整合了很多.net core的新技术和相关应用场景,虽然最早开始ABP框架是基于.net framework,后来也全部转向 ...