把字符串轉換成整數 -python


思路:從后往前遍歷字符串,先不處理第一個字符,因為他可能是一個表示正負符號的字符。等除第一個都處理完了,再處理第一個字符就可以了

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        # write code here
        if len(s) == 0:
            return 0
        num = [str(i) for i in range(10)]
        res = 0
        cnt = 0
        for i in range(len(s)-1,0,-1):
            if s[i] not in num:
                return 0
            else:
                res += 10**cnt*int(s[i])
            cnt += 1
        if s[0] in num:
            res += 10 ** cnt * int(s[0])
            return res
        elif s[0] == '+':
            return res
        elif s[0] == '-':
            return -1*res
        else:
            return 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM