剑指offer 50 把字符串转换成整数
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 输入描述: 输入一个字符串,包括数字字母符号,可以为空 输出描述: 如果是合法的数值表达则返回该数字,否则返回0 示例1 输入
+2147483647 1a33 输出
2147483647 0
思路
需要判断各种异常条件。
代码
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
num = 0
if len(s) == 0:
return 0
if len(s) == 1:
if s[0] <= 9 and s[0] >= 0:
return ord(s[0]) - ord(0)
else:
return 0
flag = 1
if s[0] == -:
flag = -1
elif s[0] == +:
flag = 1
elif s[0] <= 9 and s[0] >= 0:
num += ord(s[0]) - ord(0)
else:
return 0
for index in range(1, len(s)):
if s[index] <= 9 and s[index] >= 0:
num = num * 10 + (ord(s[index]) - ord(0))
else:
return 0
return num * flag
