leetcode-008-String to Integer (atoi)

来源:互联网 发布:内部类java 编辑:程序博客网 时间:2024/06/05 21:07

  • 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 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)
0 0