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

原文地址:https://www.cnblogs.com/fangdai/p/6689608.html