atoi

题目描述

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.

解题方法

string to integer, 遇到不是number的character就停止,将之前的变为int

  1. 首先要去掉两边的whitespace, python string提供了strip()函数,如果不用的话可以用指针解决
  2. 要判断是否有sign, sign也只能在第一个,所以判断之后去掉
  3. 对于后面的就比较简单了,遇到非Number的就停止,其余的不断加到result里
  4. 最后在处理一下overflow的问题

Solution

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0 
        str = str.strip()
        length = len(str)
        isNegative = False
        pointer = 0
        if pointer == length:
            return 0

        if str[pointer] == "-":
            isNegative = True
            pointer += 1
        elif str[pointer] == "+":
            pointer += 1

        result = 0
        while pointer < length:
            if not str[pointer].isdigit():
                break
            else:
                result *= 10
                result += int(str[pointer])
                pointer += 1

        if isNegative and result > 2147483648:
            return -2147483648
        elif not isNegative and result > 2147483647:
            return 2147483647

        if isNegative:
            return -1 * result
        else:
            return result

Reference