zoukankan      html  css  js  c++  java
  • LeetCode No.8. String to Integer (atoi) 2017/4/10(补上一周)

    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.

    题目大意:将字符串转换为整数

    解题思路:其实该题的关键是按照所有可能输入的情况分情况讨论,一开始想到的是不合法输入、正负号以及超出整数范围这几种情况,后来运行过后未通过,才发现还应该处理空格、空字符串的情况。

    因此,首先用一个变量来保存符号,判断输入的内容是否合法或为空字符串,是就返回0.然后用Python函数strip删除空格,判断符号,最后判断是否超出整数范围。

    代码如下:

    class Solution(object):
      def myAtoi(self, str):
      """
      :type str: str
      :rtype: int
      """
        answer = 0
        sign = 1
        if str == "" or not str:
        return 0
        str = str.strip()
        if str[0] == '+':
        str = str[1:]
        elif str[0] == '-':
        sign = -1
        str = str[1:]
        for i in str:
        if i >= '0' and i <= '9':
        answer = 10 * answer + ord(i) - ord('0')
        else:
          break
        answer = sign * answer
        if answer > 2147483647:
          answer = 2147483647
        elif answer < -2147483648:
          answer = -2147483648
        return answer

  • 相关阅读:
    idea 文件名乱码问题的解决
    <context:component-scan>使用说明
    <mvc:annotation-driven />
    mac下的一些常识
    centos下的防火墙配置
    mac 下安装nginx
    centos下安装nginx
    Centos-统计文件或目录占用磁盘空间-du
    Centos-查看磁盘分区占用情况-df
    Centos-重定向方式打包、备份、还原、恢复工具-cpio
  • 原文地址:https://www.cnblogs.com/fangdai/p/6689608.html
Copyright © 2011-2022 走看看