Python程式設計實現自己的atoi()函式
給定一個可能表示數字的字串,如果它是一個有效的數字,則必須使用Python程式語言將其轉換為整數。atoi()函式用於C程式語言,用於將作為引數傳遞給它的字串轉換為整數值(如果字串是有效的整數),否則它會顯示未定義的行為。
示例
輸入1
string S = "9834"
輸出
9834
解釋
給定一個表示數字的字串,因此我們得到了相同的輸出。
輸入2
string S = "09 uy56"
輸出
Invalid Input
解釋
給定的字串不是有效的整數,因為它包含空格和小寫英文字母,因此我們給出了相應的輸出。
輸入3
string str = "-987"
輸出
-987
字串有效
在這種方法中,我們將假設給定的字串是有效的字串,並且在字串的開頭、中間或結尾不會包含任何空格。
此字串僅包含數字,並且可能包含一個'-'字元,表示該數字為負數。
在這種方法中,首先,我們將建立一個函式,該函式將接受單個引數並返回作為答案的整數。
對於負數,其前面會有一個減號,這意味著我們必須檢查索引零處的字元是否為'-'。
我們將遍歷字串,並維護一個數字來儲存答案。在每個索引處,我們將當前數字乘以10以增加一個小數位,然後將當前數字新增到其中。
最後,我們將返回最終答案,讓我們看看完整的程式碼
示例
# function to converting the string to an integer def atoi(str): # Assuming the string is valid neg = 1 # checking for the negative number if (str[0] == '-'): neg = -1 ans = 0 i = 0 # if the number is the negative number then start from the next index if(neg == -1): i = i + 1 while (i < len(str)): cur = (int)(str[i]) ans = ans * 10 + cur i = i + 1 ans = ans* neg return ans; # returning the answer # defining the input and calling the function str = "-354663"; # calling the function ans = atoi(str) # printing the answer print("The value of the current number is:" , ans)
輸出
The value of the current number is -354663
時間和空間複雜度
上述程式碼的時間複雜度為O(N),其中N是給定字串中字元的數量。
上述程式碼的空間複雜度為O(1),因為我們沒有使用任何額外的空間。
字串可能無效
在這個程式中,我們將檢查當前字串是否可能無效,因此我們將新增一個條件:如果字串包含任何不在'0'到'9'範圍內的字元,我們將返回“無效字串”作為輸出,否則我們將按照前面方法中定義的步驟獲取輸出。
此外,我們將使用Python程式語言的ord函式來獲取當前字元的ASCII值,並將它們新增到儲存答案的數字中。
示例
# function for converting the string to an integer def atoi(str): # Assuming the string is valid neg = 1 # checking for the negative number if (str[0] == '-'): neg = -1 ans = 0 i = 0 # if the number is negative number then start from the next index if(neg == -1): i = i + 1 while (i < len(str)): # Checking for the base conditions # if the current character is not a digit return the invalid answer if((ord(str[i]) > ord('9')) or (ord(str[i]) < ord('0'))): print("The given string represents the invalid number") return cur = (int)(str[i]) ans = ans * 10 + cur i = i + 1 ans = ans* neg # printing the answer print("The value of the current number is:", ans); # defining the input and calling the function str = "-354 663"; # Calling the function atoi(str)
輸出
The given string represents the invalid number
時間和空間複雜度
上述程式碼的時間複雜度為O(N),其中N是給定字串中字元的數量。
上述程式碼的空間複雜度為O(1),因為我們沒有使用任何額外的空間。
結論
在本教程中,我們實現了一個Python程式,用於將以字串形式存在的數字轉換為整數。我們遍歷了字串,並檢查當前字串是否表示有效數字。我們使用了ord() Python函式來獲取字元的ASCII值並將其新增到答案中。