zoukankan      html  css  js  c++  java
  • leetcode-easy-string- 8 String to Integer (atoi)

    mycode  98.26%

    易错点: while循环式,and判断的地方先判断下标会不会超出范围

    class Solution(object):
        def myAtoi(self, str):
            """
            :type str: str
            :rtype: int
            """
            str = str.strip()
            if not str :
                return 0
            res , start = '' , 0
            if str[0] == '-' or str[0] == '+' :
                res = str[0]
                start = 1 
            if start >= len(str) or not str[start].isnumeric() :
                return 0
            while start < len(str) and str[start].isnumeric():
                res += str[start]
                start += 1
            res = int(res) 
            if res > 2147483647 :
                res = 2147483647 
            elif res <  -2147483648:
                res = -2147483648
            return res
            

    参考

    思路:哪些情况下可以直接返回0呢 1) 空 2)+-符号不是开头3) 遍历到的字符不是空格、+-、数字

     def myAtoi(self, S):
            """
            :type str: str
            :rtype: int
            """
            res = ''
            
            S1 = S.strip() # need to know
            
            for s in S1:   
                if s == '': continue
                if res != '' and s in '+-': break   
                if s in '-+0123456789':  # need to know
                    res += s
                else:
                    break
               
            if res == '' or res == '+' or res== '-': 
                return 0
            elif int(res) < -2**31: 
                return -2**31
            elif int(res) > (2**31)-1:
                return (2**31) -1
            else: 
                return int(res)
  • 相关阅读:
    win10上使用linux命令
    leetcode--js--Median of Two Sorted Arrays
    leetcode--js--Longest Substring Without Repeating Characters
    Linux常用的命令
    微信小程序
    leetcode—js—Add Two Numbers
    PHPExcel使用
    console控制台的用法
    git中常混淆的操作
    mysql解析json下的某个字段
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10996637.html
Copyright © 2011-2022 走看看