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.

思路


  这道题的主要难点在于对于异常情况的考虑需要周全,字符数字前面出现字母,正负号,空字符,最大范围情况。都需要考虑。时间复杂度为O(n), 空间复杂度为O(1)。

解决代码


 class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip() # 去除前后的空格
if len(str) < : # 如果长度小于1直接返回0
return
neg_falg = False # 设置负数标志位
if str[] == '-' or str[]== '+': # 判断第一位是否带有正负符号
neg_falg = True if str[] == '-' else False # 负号时设置标志量为负,正好时不做改变。
str = str[:] # 并且去除符号
res = 0 # 最终结果存储
for i in str:
if ord(i) >= and ord(i) <= : # 判断该字符是否属于数字范围中
res = res* + (ord(i)-ord('')) # 求出结果
else:
if res == : # 如果不属于,则判断res结果,直接返回
return
break # 终止循环
if neg_falg: # 根据标志位来判断是否为负数
res = - res
if res > pow(, )- or res < -pow(,): # 判断是否溢出
return pow(, )- if res > pow(, )- else -pow(,)
return res # 返回结果

【LeetCode每天一题】String to Integer (atoi)(字符串转换成数字)的更多相关文章

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

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

  2. leetcode第八题 String to Integer (atoi) (java)

    String to Integer (atoi) time=272ms   accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...

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

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

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

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

  5. [leetcode]经典算法题- String to Integer (atoi)

    题目描述: 把字符串转化为整数值 原文描述: Implement atoi to convert a string to an integer. Hint: Carefully consider al ...

  6. leetcode第八题--String to Integer (atoi)

    Problem: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible inp ...

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

    [抄题]: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: T ...

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

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

  9. LeetCode【8】. String to Integer (atoi) --java实现

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

随机推荐

  1. 我是怎样使用javassist将代码注入到帝国OL并进行调试的

    帝国OL是拉阔一款手机网络游戏(腾讯也有代理),我在中学时代玩儿过. 帝国OL还维护着KJava版本游戏客户端,这意味着我们可以在PC端使用模拟器玩儿游戏. 不过这篇文章我主要是关注如何通过代码注入拦 ...

  2. nginx js、css、图片 及 一些静态文件中出现 http://upstreamname:port 导致部分网页样式显示不正常

    nginx js.css.图片 及 一些静态文件中出现 http://upstreamname:port 导致部分网页样式显示不正常 http://upstreamname:port/....../. ...

  3. Docker、kubernetes、微服务、SpringBoot/Cloud...好乱!到底要不要学?

    Docker.微服务日益火热的今天,相信标题上这些名词大家都不陌生.但也相信有很多同学并不够清楚他们的概念,不理解它们的关系,也可能有这样的疑惑:不知道跟我有没有关系?要不要学习?怎么去学习?学哪些东 ...

  4. 牛客多校10 D Rikka with Prefix Sum 不是数据结构

    https://www.nowcoder.com/acm/contest/148/D 题意: 1e5个数,1e5个操作,操作分为: 1.区间加. 2.整个数列替换为前缀和. 3.区间查询. 查询数小于 ...

  5. linux:基本概念和操作

    1. 终端 Linux 默认提供了 6 个纯命令行界面的 “terminal”(准确的说这里应该是 6 个 virtual consoles)来让用户登录,在物理机系统上你可以通过使用[Ctrl]+[ ...

  6. [ovs] openvswitch ovs ovs-vsctl ovs-appctl 命令行参数自动补全 bash bash-completion

    1, 安装bash_completion: [root@vrouter1 ~]# yum install bash-completio 2,  找到你的ovs的补全脚本装在了哪里 [root@vrou ...

  7. [daily] 在CentOS7中使用 sanitizer-address 发现内存问题 / CentOS7使用SCLo软件源安装devtoolset软件

    接前文: [daily] 内存越界的分析与定位 如前文提及, 使用sanitizer-address 可以有效的检查程序的内存问题. 当时在CentOS7中,虽然也可以使用,但是却遇到如下两个问题: ...

  8. [daily][archlinux][pacman] 删除所有孤立包(orphan)

    ‎[:] ‎<‎tong‎>‎ sudo pacman -Rsun `pacman -Qdt |cut -d` ‎[:] ‎<‎tong‎>‎ 我每次都这么删, 有没有高级点的 ...

  9. ms sql server 游标

    很简单的一个小例子. /****** Object: StoredProcedure [dbo].[usp_test] Script Date: 10/28/2016 15:08:31 ******/ ...

  10. 【Java】一台服务器配置多个Tomcat

    需求缘由 最近接收了一个新的工具业务:ipublish发布系统,刚接手这个业务的时候,发现每次发布新的代码 需要到群里告知大家,我要停服务几分钟,准备更新代码啦.这尼玛 哪个公司都不敢这么牛逼的和用户 ...