Python编程实现自己的atoi()函数


给定一个可能表示数字的字符串,如果它是一个有效的数字,则必须使用Python编程语言将其转换为整数。atoi()函数用于C编程语言,用于将作为参数传递给它的字符串转换为整数值(如果字符串是有效的整数),否则它会显示未定义的行为。

示例

输入1

string S = "9834"

输出

9834

解释

给定一个表示数字的字符串,因此我们得到了相同的输出。

输入2

string S = "09 uy56"

输出

Invalid Input 

解释

给定的字符串不是有效的整数,因为它包含空格和小写英文字母,因此我们给出了相应的输出。

输入3

string str = "-987"

输出

-987

字符串有效

在这种方法中,我们将假设给定的字符串是有效的字符串,并且在字符串的开头、中间或结尾不会包含任何空格。

此字符串仅包含数字,并且可能包含一个'-'字符,表示该数字为负数。

在这种方法中,首先,我们将创建一个函数,该函数将接受单个参数并返回作为答案的整数。

对于负数,其前面会有一个减号,这意味着我们必须检查索引零处的字符是否为'-'。

我们将遍历字符串,并维护一个数字来存储答案。在每个索引处,我们将当前数字乘以10以增加一个小数位,然后将当前数字添加到其中。

最后,我们将返回最终答案,让我们看看完整的代码

示例

Open Compiler
# 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),因为我们没有使用任何额外的空间。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

字符串可能无效

在这个程序中,我们将检查当前字符串是否可能无效,因此我们将添加一个条件:如果字符串包含任何不在'0'到'9'范围内的字符,我们将返回“无效字符串”作为输出,否则我们将按照前面方法中定义的步骤获取输出。

此外,我们将使用Python编程语言的ord函数来获取当前字符的ASCII值,并将它们添加到存储答案的数字中。

示例

Open Compiler
# 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值并将其添加到答案中。

更新于:2023年7月11日

浏览量:328

开启你的职业生涯

通过完成课程获得认证

开始学习
广告