实现atoi函数(string转integer)
来源:互联网 发布:黑马程序员官网 编辑:程序博客网 时间:2024/05/22 09:47
实现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
思路
- 利用Python内置的int(str)函数可以将字符串快速转换成int型
- 利用int(str)是否抛出异常来快速判断str能否被转换成int,进而迅速确定输入字符串中第一个非数字字符的位置
- 需要注意处理
+
,-
符号的问题
代码
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地址
阅读全文
0 0
- 实现atoi函数(string转integer)
- 实现String to Integer (atoi)
- 【String转Integer】String to Integer (atoi)
- String to Integer (atoi) C++实现
- <leetcode系列> String to Integer (atoi) 以及atoi源码实现
- String to Integer (atoi) 字符串转整数
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- BZOJ 3993: [SDOI2015]星际战争 二分+网络流
- 使用ReadFile程序崩溃的原因
- Flink-Table-SQL系列之source
- python函数2
- RcppArmadillo简明手册
- 实现atoi函数(string转integer)
- Java编程思想第四版课后习题--经典
- RIDE加载Selenium2Library总是显示红色的解决办法
- 排序总结
- 打劫房屋III
- 第一次就记录给java的第五次作业吧
- insmod: can't insert 'led.ko': invalid module format
- spring是什么鬼
- 【数据结构】单链表--进阶题目