每日一练3

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。

函数 myAtoi(string s) 的算法如下:

  1. 空格:读入字符串并丢弃无用的前导空格(" "
  2. 符号:检查下一个字符(假设还未到字符末尾)为 '-' 还是 '+'。如果两者都不存在,则假定结果为正。
  3. 转换:通过跳过前置零来读取该整数,直到遇到非数字字符或到达字符串的结尾。如果没有读取数字,则结果为0。
  4. 舍入:如果整数数超过 32 位有符号整数范围 [−231,  231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被舍入为 −231 ,大于 231 − 1 的整数应该被舍入为 231 − 1 。

返回整数作为最终结果。

示例 1:

输入:s = "42"

输出:42

解释:加粗的字符串为已经读入的字符,插入符号是当前读取的字符。

带下划线线的字符是所读的内容,插入符号是当前读入位置。
第 1 步:"42"(当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"42"(读入 "42")
           ^

示例 2:

输入:s = " -042"

输出:-42

解释:

第 1 步:"   -042"(读入前导空格,但忽视掉)
            ^
第 2 步:"   -042"(读入 '-' 字符,所以结果应该是负数)
             ^
第 3 步:"   -042"(读入 "042",在结果中忽略前导零)

这是我原本写的,比较复杂且不够高效,时间复杂度太大。

def myAtoi(self, s: str) -> int:
        def turn(n_s):
            re = ""
            n = len(n_s)-1
            i=0
            while n_s[i]>="1" and n_s[i]<="9":
                re = re+n_s[i]
                if i<n:
                    i+=1
            return re

        def blank(s:str,form:str):
            n_s = s
            while n_s[0]==form:
                n_s = n_s[1:]
            return n_s
        
        def contr(a):
            n_s = blank(a,"0")
            if n_s[0]<"0" or n_s>"9":
                return 0
            else:
                return int(turn(n_s))

        n_s = blank(s," ")
        if n_s[0]=="-":
            res = -contr(n_s[1:])
            if res<-2**31:
                return -2**31
            else:
                return res
        elif n_s[0]=="+" or n_s[0]>="0" and n_s[0]<="9":
            res = contr(n_s[1:])
            if res>2**31-1:
                return 2**31-1
            else:
                return res
        else:
            return 0

 虽然思路没错,甚至结果也对,但是不够抽象,并且整合重复性太大,真·屎山......

其实是我太懒,有些python的语法都忘了,导致什么函数都要自己写,然后我就回去review了一下。

def myAtoi(self, s: str) -> int:
        # 去除前导空格
        s = s.lstrip()
        
        # 检查字符串是否为空或第一个字符不是正负号或数字
        if not s or s[0] not in ('+', '-') and not s[0].isdigit():
            return 0
        
        # 初始化结果和索引
        result = 0
        index = 0
        
        # 如果有符号位,跳过
        if s[index] in ('+', '-'):
            sign = -1 if s[index] == '-' else 1
            index += 1
        else:
            sign = 1
        
        # 遍历字符串,直到遇到非数字字符为止
        while index < len(s) and s[index].isdigit():
            digit = int(s[index])
            
            # 检查溢出情况
            if (result > (2**31 - 1 - digit) // 10) or (result == (2**31 - 1 - digit) // 10 and digit > 7):
                return 2**31 - 1 if sign > 0 else -2**31
                
            result = 10 * result + digit
            index += 1
        return sign * result

if __name__=='__main__':
    s = "-213snal"
   print(myAtoi(s))

这是优化后的,效果还不错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值