安全性を証明する:文字列を整数に変換します

タイトル説明
文字列を整数に変換し、ライブラリ機能を使用することはできません要求は整数文字列を変換します。0の値または文字列が有効な戻り値ではありません0

入力説明は
nullにすることができ、英数字記号を含む文字列を入力してください

出力説明
式が有効な数値は0それ以外の場合は、返されている場合

例1つの
入力
+2147483647
1a33
出力
2147483647
0

その答えの一部、より賢いです

class Solution:
    def StrToInt(self, s):
        # write code here
        if s is '':
            return 0
        numlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        res = 0
        label = 1
        first = s[0]
        if first == '+':
            label = 1
            s = s[1:]
        elif first == '-':
            label = -1
            s = s[1:]
        for string in s:
            if string not in numlist:
                return 0
            else:
                res = res * 10 + numlist.index(string)
        return label * res
公開された82元の記事 ウォン称賛82 ビュー240 000 +

おすすめ

転載: blog.csdn.net/uncle_ll/article/details/104183339