摘要:實現(xiàn)函數(shù)轉(zhuǎn)思路利用內(nèi)置的函數(shù)可以將字符串快速轉(zhuǎn)換成型利用是否拋出異常來快速判斷能否被轉(zhuǎn)換成,進而迅速確定輸入字符串中第一個非數(shù)字字符的位置需要注意處理符號的問題代碼如果是或者但是會拋出異常,此時返回由于的沒有取值上限,如果規(guī)定為
實現(xiàn)atoi函數(shù)(string轉(zhuǎn)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思路
利用Python內(nèi)置的int(str)函數(shù)可以將字符串快速轉(zhuǎn)換成int型
利用int(str)是否拋出異常來快速判斷str能否被轉(zhuǎn)換成int,進而迅速確定輸入字符串中第一個非數(shù)字字符的位置
需要注意處理+,-符號的問題
代碼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沒有取值上限,如果規(guī)定int為32位,需要判斷int(retstr)是否大于2147483647或者小余-2147483648 return int(retstr) except: return 0
本題以及其它leetcode題目代碼github地址: github地址
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/38652.html
摘要:通用方法復(fù)雜度時間空間思路字符串題一般考查的都是邊界條件特殊情況的處理。所以遇到此題一定要問清楚各種條件下的輸入輸出應(yīng)該是什么樣的。 String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input...
摘要:難度是標(biāo)準(zhǔn)庫中的一個函數(shù)可以將字符串表示的整數(shù)轉(zhuǎn)換為現(xiàn)在要求我們自己來實現(xiàn)它解題過程中主要有以下兩點需要注意字符串開頭可能出現(xiàn)或者需要處理使用來記錄中間結(jié)果防止溢出下面是的解法 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If ...
摘要:判斷一條單向鏈表是不是回文解法可以借助棧,將遍歷到的前半段鏈表節(jié)點放入棧,后半段每當(dāng)遍歷到一個,都要與出棧的節(jié)點相比較。如果中間出現(xiàn)不相等的情況,則不是回文。 [July 程序員編程藝術(shù):面試和算法心得題目及習(xí)題][1] 字符串轉(zhuǎn)換成整數(shù) also Leetcode 8 String to Integer (atoi) 題目描述 輸入一個由數(shù)字組成的字符串,把它轉(zhuǎn)換成整...
Problem Implement function atoi to convert a string to an integer. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values...
摘要:若函數(shù)不能執(zhí)行有效的轉(zhuǎn)換,返回。如果數(shù)值超過可表示的范圍,則返回或。示例輸入輸出解釋轉(zhuǎn)換截止于數(shù)字,因為它的下一個字符不為數(shù)字。 這是我參與11月更文挑戰(zhàn)的第12天。一、寫在前面LeetCode 第一題兩數(shù)之和傳輸門:聽說你還在寫雙層for循環(huán)解兩數(shù)之和?LeetCode 第二題兩數(shù)之和傳輸門:兩個排序數(shù)組的中...
閱讀 1392·2021-11-22 14:44
閱讀 2520·2021-09-30 09:47
閱讀 1298·2021-09-09 11:56
閱讀 2184·2021-09-08 09:45
閱讀 4271·2021-08-31 09:40
閱讀 1313·2019-08-30 15:52
閱讀 2120·2019-08-30 14:09
閱讀 1684·2019-08-26 17:04