剑指offer 把字符串转换成整数 python

题目描述

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

样例

输入

+2147483647
    1a33

输出

2147483647
    0

想法:
很简单,从后往前遍历,然后与10的次方相乘后相加,还需要判断最前面的符号,最后返回总和与符号的乘积

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if s == '':
            return 0
        ret = 0
        num = 0
        fuhao = 1
        for i in s[::-1]:
            if i < '0' or i > '9':
                if i == '-':
                    fuhao = -1
                    continue
                elif i == '+':
                    continue
                else:
                    return 0
            ret += int(i) * pow(10, num)
            num += 1
        return ret*fuhao

最后

刷过的LeetCode源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

posted @ 2018-09-28 20:24  GF66  阅读(282)  评论(0编辑  收藏  举报