(牛客网)字符串-把字符串转换成整数(Python)

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

输入描述:

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

输出描述:

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

示例1

输入

+2147483647
    1a33

输出

2147483647
    0

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if s == "":
            return 0
        if s == "+" or s == "-":
            return 0
        res = []
        a = ['q','a','z','x','s','w','e','d','c','v','f','r','t','g','b','n','h','y','u','j','m','k','i','o','l','p']
        b = ['0','1','2','3','4','5','6','7','8','9']
        c = ['+','-']
        lis = list(s)
        for i in lis:
            if i in a:
                return 0
            elif i not in a:
                res.append(i)
        return int(''.join(res))
         
        
        

猜你喜欢

转载自blog.csdn.net/qq_42633819/article/details/88606283