[剑指Offer]把字符串转换成整数

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

输入描述:

输入一个字符串,包括数字字母符号,可以为空

输出描述:

如果是合法的数值表达则返回该数字,否则返回0

示例1

输入

+2147483647
1a33

输出

2147483647
0

解题思路

略。

代码

Python(2.7.3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if len(s) == 0 or (len(s) == 1 and (s[0] == '+' or s[0] == '-')):
return 0
num = 0
minus = False
if s[0] == '+':
s = s[1:]
elif s[0] == '-':
minus = True
s = s[1:]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for i in s:
if i in numbers:
num = 10 * num + numbers.index(i)
else:
return 0
if minus:
return -num
return num

运行时间:25ms
占用内存:5752k