zoukankan      html  css  js  c++  java
  • 139-8. 字符串转换整数 (atoi)

    请你来实现一个 atoi 函数,使其能将字符串转换成整数。(前两个我写的,效率不是很高)
    class Solution(object):
        def myAtoi1(self, s):
            """
            :type s: str
            :rtype: int
            """
            temp = s.strip()
            if not temp:
                return 0
    
            if temp[0].isalpha():
                return 0
    
            symbol_list = ["+", "-"]
            ret_str = ""
            for i in range(len(temp)):
                if i == 0 and temp[i] in symbol_list:
                    ret_str += temp[i]
                    continue
    
                if not temp[i].isdigit():
                    break
                ret_str += temp[i]
    
            ret_num = int(ret_str) if ret_str and ret_str not in symbol_list else 0
            if -2 ** 31 < ret_num < 2**31:
                return ret_num
            else:
                if ret_num > 0:
                    return 2**31 - 1
                else:
                    return -2 ** 31
    
        def myAtoi2(self, s):
            """
            :type s: str
            :rtype: int
            """
            temp = s.strip()
            if not temp:
                return 0
    
            if temp[0].isalpha():
                return 0
    
            symbol_list = ["+", "-"]
            symbol = ""
            start = 0
            end = 0
            for i in range(len(temp)):
                if i == 0 and temp[i] in symbol_list:
                    symbol += temp[i]
                    start += 1
                    end += 1
                    continue
    
                if not temp[i].isdigit():
                    break
                end += 1
    
            ret_num = int(symbol + temp[start: end]) if temp[start: end] else 0
            if -2 ** 31 < ret_num < 2**31:
                return ret_num
            else:
                if ret_num > 0:
                    return 2**31 - 1
                else:
                    return -2 ** 31
    
        def myAtoi(self, s):
            """这个代码写的漂亮"""
            return max(min(int(*re.findall('^[+-]?d+', s.lstrip())), 2**31 - 1), -2**31)
    
    
    if __name__ == '__main__':
        import re
        s1 = Solution()
        s = "3.14159"
        print(s1.myAtoi(s))
    
  • 相关阅读:
    自娱自乐
    项目冲刺(2)-第二、第三天
    项目冲刺(2)-第一天
    Beta版本冲刺计划及安排
    第一章 构造过程抽象
    python 学习2
    python 学习1
    ionic 初入门
    NodeJS学习
    软件工程实践总结作业——个人作业
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14267692.html
Copyright © 2011-2022 走看看