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))
    
  • 相关阅读:
    web网络编程
    C++ 多线程*****(看书补充)
    C++信号处理
    预指令
    C++模板*******
    C++ 命名空间
    动态存储
    异常处理**********
    私钥、秘钥详解
    Pod控制器应用进阶
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14267692.html
Copyright © 2011-2022 走看看