實現atoi函數(string轉integer)

實現atoi函數(string轉integer)

String to Integer (atoi)

  • Implement atoi to convert a string to an integer.
  • Hint: Carefully consider all 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..

  • Example 1:

Input: ""
Output: 0
  • Example 2:
Input: "+2"
Output: 2
  • Example 3:
Input: "+-2"
Output: 0
  • Example 4:
Input: "+"
Output: 0
  • Example 5:
Input: "-223pasudasd"
Output: -223

思路

  1. 利用Python內置的int(str)函數可以將字符串快速轉換成int型
  2. 利用int(str)是否拋出異常來快速判斷str能否被轉換成int,進而迅速確定輸入字符串中第一個非數字字符的位置
  3. 需要注意處理+,-符號的問題

代碼

class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip()
        retstr = ''
        try:
            for _, item in enumerate(s):
                if item == '+' or item == '-':
                    retstr += item
                else:
                    retstr += str(int(item))
        finally:
            if len(retstr) == 0:
                return 0
            else:
                try:
                    # 如果 retstr 是 '-' 或者 '+',len(retstr) != 0 但是會拋出異常,此時返回0
                    # 由於python的int沒有取值上限,如果規定int爲32位,需要判斷int(retstr)是否大於2147483647或者小余-2147483648
                    return int(retstr)
                except:
                    return 0

本題以及其它leetcode題目代碼github地址: github地址

發佈了29 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章