leetcode-008-String to Integer (atoi)

P008 String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

思路分析

关键是注意特殊情况的处理:

  • 输入空字符==>0
  • 对输入进行trim
  • 注意可能出现的正号(+)和负号(-)
  • 读取到非字符时停止,并将前面的结果返回
  • 注意溢出问题==> Integer.MAX_VALUE 或者 Integer.MIN_VALUE

代码

java

public class Solution008 {
    public int myAtoi(String str) {
        if (str == null)
            return 0;
        str = str.trim();
        if ("".equals(str))
            return 0;

        StringBuilder sb = new StringBuilder();
        int sign = 1;
        if (str.startsWith("+")) {
            str = str.replaceFirst("\\+", "");
        } else if (str.startsWith("-")) {
            sign = -1;
            str = str.replaceFirst("-", "");
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c > '9' || c < '0') {
                break;
            }
            sb.append(c);
        }
        try {
            long l = sign * Long.parseLong(sb.toString());
            if (l >= Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (l <= Integer.MIN_VALUE)
                return Integer.MIN_VALUE;

            return (int) (l);
        } catch (Exception e) {
            // e.printStackTrace();
            return 0;
        }
    }

    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        Solution008 s8 = new Solution008();
        String strs[] = { //
                "", "-2147483648", "-2147483649", "2147483648", "-2147483648", //
                "1010023630", "-1010023630", //
                "   10522545459", " 10522545459+123 ", //
                "-123", "+123", " -123 ", "+123sdf", //
                "11111111111111111111111111111111111111111111111111", //
                "sfjdk", "-fjdks", "+fjsdk" };
        for (String s : strs) {
            System.out.println(s + "-->" + s8.myAtoi(s));
        }
    }
}

python

class Solution008(object):
    def myAtoi(self, s):
        """
        :type str: str
        :rtype: int
        """

        if not s:return 0
        s = s.strip()

        if "" == s:return 0
        sign = 1;strs = "0"

        if s[0] == "+":
            s = s[1:]
        elif s[0] == "-":
            sign = -1
            s = s[1:]

        for c in s:
            if c > '9' or c < '0':
                break
            strs += c

        l = long(strs) * sign

        if l <= -2147483648:return - 2147483648
        if l >= 2147483647:return 2147483647

        return (int)(l)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值