LeetCode:008 String to Integer (atoi)

本题的题型内容如下:
这里写图片描述
本题的解决思路主要注意一下几点:
1,当输入为空时的处理;
2,前面的空白字符的处理
3,如何得到前面的正负号
4,注意最大值和最小值,防止溢出
算法实现
java

class Solution {
    public int myAtoi(String str) {
        int index = 0;
        int total = 0;
        int sign = 1;

        // Check if empty string
        if(str.length() == 0)
            return 0;

        // remove white spaces from the string
        while(index < str.length() && str.charAt(index) == ' ')
            index++;

        if (index == str.length()) return 0;

        // get the sign
        if(str.charAt(index) == '+' || str.charAt(index) == '-') {
            sign = str.charAt(index) == '+' ? 1 : -1;
            index++;
        }

        // convert to the actual number and make sure it's not overflow
        while(index < str.length()) {
            int digit = str.charAt(index) - '0';
            if(digit < 0 || digit > 9) break;

            // check for overflow
            if(Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;

            total = total*10 + digit;
            index++; // don't forget to increment the counter
        }
        return total*sign;
    }
}

python:

class Solution:
    def myAtoi(self,str):
        """
        :type str:str
        :rtype int
        """
        str=str.strip()
        number=""

        for x in str:
            if x.isalpha() and number =="":
                return 0
            elif x.isalpha():
                break
            elif x==".":
                break
            elif x==" ":
                break
            elif(x=="+" or x=="-") and number=="":
                number=number+x
            elif(x=="+" or x=="-") and number!="":
                break
            elif (x=="+" or x=='-') and (number[-1]=="+" or number[-1]=="-"):
                return 0
            elif (x=="+" or x=="-") and ("+" in number or "-"in number):
                break
            elif x.isdigit():
                number=number+x
        if number ==""or number =="+" or number =="-":
            return 0
        else:
            if int(number)>((2**31)-1):
                return (2**31)-1
            elif int(number)<-(2**31):
                return -(2**31)
            else:
                return int(number)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值