把字符串转换成整数

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

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def StrToInt(self, s):
 4         n = len(s)
 5         if n == 0:
 6             return 0
 7         isNegative =  False
 8         if s[0] == '-':
 9             isNegative = True
10         ret = 0
11         for i in range(n):
12             c = s[i]
13             if i == 0 and (c == '+' or c == '-'):
14                 continue
15             if c < '0' or c >'9':
16                 return 0
17             ret = ret * 10 + (ord(c) - ord('0'))
18         return -ret if isNegative else ret
19         # write code here

 

posted on 2019-06-14 20:23  Sempron2800+  阅读(114)  评论(0编辑  收藏  举报