天天看点

leetcode-008-String to Integer (atoi)P008 String to Integer (atoi)

  • P008 String to Integer atoi
    • 思路分析
    • 代码
      • java
      • python

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 ;
        str = str.trim();
        if ("".equals(str))
            return ;

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

        for (int i = ; 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 ;
        }
    }

    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 
        s = s.strip()

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

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

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

        l = long(strs) * sign

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

        return (int)(l)