iT邦幫忙

0

leetcode with python:8. String to Integer (atoi)

  • 分享至 

  • xImage
  •  

題目:

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:
1.Read in and ignore any leading whitespace.
2.Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3.Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4.Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
5.If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
6.Return the integer as the final result.

Note:
Only the space character ' ' is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

實作出atoi函數,一個從字串讀取數字的函數,執行如下:
1.忽略最前頭的空白
2.接著遇到的第一個字元若是'+'或'-',則決定該數字的正負
3.持續讀取數字字元直到遇到非數字字元為止
4.將讀取到的數字字串轉為數字,若2.有記錄到'+'或'-',則依其更改正負
5.若轉換後數字超出[-2^31, 2^31 - 1],則將其紀錄為邊界值
ex:2^31紀錄為2^31 - 1

題目都快把怎麼實作講完了
我還蠻討厭這種難度設立在繁瑣條件上的題目

class Solution:
    def myAtoi(self, s: str) -> int:
        x=""
        y=""
        start=0
        num="0123456789"
        
        for i in range(len(s)): #略過開頭空白
            if s[i] != " ":
                start=i
                break
        
        for i in range(start,len(s)):
            if s[i]=="-" or s[i]=="+":
                if x=="" and y=="":
                    x=s[i]
                else: #若'+','-'不在第一位,也相當於遇到非數字字元,停止紀錄
                    break
            elif s[i] in num:
                y=y+s[i]
            else:
                break
                
        if y=="": #若沒紀錄到任何數字,回傳0
            return 0
        
        if x=="-": #將超出範圍的值改為邊界值
            if int(y)>2147483648:
                return -2147483648
            else:
                return -int(y)
        else:
            if int(y)>2147483647:
                return 2147483647
            else:
                return int(y)

建立兩個字串x,y分別記錄正負和數字字串
先用迴圈跳過空白找出起始點
若第一位是'+','-'就紀錄在x,不是就直接開始記錄數字到y
接著開始記錄數字,直到遇到非數字字元或陣列尾端
最後轉換並回傳紀錄下來的數字,若超出範圍就將其改為邊界值
最後執行時間36ms(faster than 93.01%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言