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)。

解决代码


  1. class Solution(object):
  2. def myAtoi(self, str):
  3. """
  4. :type str: str
  5. :rtype: int
  6. """
  7. str = str.strip() # 去除前后的空格
  8. if len(str) < : # 如果长度小于1直接返回0
  9. return
  10. neg_falg = False # 设置负数标志位
  11. if str[] == '-' or str[]== '+': # 判断第一位是否带有正负符号
  12. neg_falg = True if str[] == '-' else False # 负号时设置标志量为负,正好时不做改变。
  13. str = str[:] # 并且去除符号
  14. res = 0 # 最终结果存储
  15. for i in str:
  16. if ord(i) >= and ord(i) <= : # 判断该字符是否属于数字范围中
  17. res = res* + (ord(i)-ord('')) # 求出结果
  18. else:
  19. if res == : # 如果不属于,则判断res结果,直接返回
  20. return
  21. break # 终止循环
  22. if neg_falg: # 根据标志位来判断是否为负数
  23. res = - res
  24. if res > pow(, )- or res < -pow(,): # 判断是否溢出
  25. return pow(, )- if res > pow(, )- else -pow(,)
  26. 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. linux下安装cmake(安装opencv库)

    apt-get install cmake cmake --version(显示版本号) cmake-gui(打开gui界面) 如果打不该GUI界面时候就需要apt-get install cmake ...

  2. 2018ACM-ICPC南京区域赛---AJGIDKM

    含[最小球覆盖][最大流isap]模板. 题面pdf https://codeforc.es/gym/101981/attachments/download/7891/20182019-acmicpc ...

  3. .NET Core开发日志——从ASP.NET Core Module到KestrelServer

    ASP.NET Core程序现在变得如同控制台(Console)程序一般,同样通过Main方法启动整个应用.而Main方法要做的事情很简单,创建一个WebHostBuilder类,调用其Build方法 ...

  4. css学习_css背景属性及其应用

    css背景属性及其应用 1.背景 2.背景简写 3.背景透明(css3) 4.背景缩放(css3) 5.多背景图片(css3) 6.凹凸文字效果

  5. SQL Server 2012 安装过程详解(包含每一步设置的含义)

    转http://www.cnblogs.com/EastLiRoar/p/4051969.html 一.启动安装程序,点击“安装”选项卡,选择“全新SQL Server独立安装或向现有安装添加功能”. ...

  6. 【待补】splay 模板

    #define _CRT_SECURE_NO_WARNINGS #include<cmath> #include<iostream> #include<stdio.h&g ...

  7. arcgis二次开发遇到System.Runtime.InteropServices.COMException (0x80040228) :异常来自HRESULT:0x80040228

    出现此问题只需要在控件上拖入一个LicenseControl就可以了 参考资料:http://yaogu.blog.163.com/blog/static/1849990662012101283256 ...

  8. Android+Tomcat通过http获取本机服务器资源

    写在前面:本博客为本人原创,严禁任何形式的转载!本博客只允许放在博客园(.cnblogs.com),如果您在其他网站看到这篇博文,请通过下面这个唯一的合法链接转到原文! 本博客全网唯一合法URL:ht ...

  9. ldap,openldap-docker,

    ldap basic and usage in devops: https://blog.csdn.net/weixin_42578481/article/details/80863890 maybe ...

  10. Coding 小技巧

    </pre>//格式化字符串的传递<p></p><p>#define  FSKILL_LOG(format ,...)   DREAMLAND_RUNI ...