题目
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
思路
- 解法一 循环
因为字符串首尾有可能时符号位,因此从第二位开始检验是否为数字。如果从第二位到末尾都是数字,那么可以计算出他们的和。然后,检验字符串的第一位,有四种可能性:
- 为‘+’
- 为‘-’
- 为数字
- 为非法字符
分别计算需要返回的num即可。
代码
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
if not s:
return 0
for i in range(1,len(s)):
if not self.verifyBit(s[i]):
return 0
num = self.caculateBit(s[1:])
if s[0] == '+':
return num
if s[0] == '-':
return -1*num
if self.verifyBit(s[0]):
return num + int(s[0])*(10**len(s[1:]))
return 0
def verifyBit(self, char):
res = False
if char >= '0' and char <= '9':
res = True
return res
def caculateBit(self, string):
res = 0
for i in range(len(string)):
res = res * 10
res += int(string[i])
return res