leetcode

 题目大意: 字符串转成整型

注意:1 、去掉数字前的空格

         2、如果数字前有“+”或者“-",判断数字的正负

         3、如果数字前有别的符号,返回0

        4、 如果数字中有非数字字符,返回该字符前的数字

       5、 由于是int型,成功读取到数字后,要判断是否溢出Integer,若溢出,返回Integer.MAX_VALUE或者Integer.MIN_VALUE思路:判断是否溢出有两种方法:

1、当num是int型, 先判断num>Integer.MAX_VALUE/10或者num<Integer.MIN_VALUE/10

    再num = num * 10 + (str.charAt(start) - '0');    

  由于,num是int型,无论如何num不会大于Integer.MAX_VALUE(int型的正负数是循环的),从而在确定num的上一步判断与Integer.MAX_VALUE/10的大小,最后在进行下一步。

2、直接把num设置成long型,

先num = num * 10 + (str.charAt(start) - '0');  //得到的是两个字符的ascii码的差值,兑换成相应的字符,而不是两个字符相减。

再判断num>Integer.MAX_VALUE或者num<Integer.MIN_VALUE    最后要转换成int类型。

public class StringtoInteger {

    public static int myAtoi(String str) {
        int start = 0;//设置指针
        boolean neg = true;
        long num = 0;    
        if (str.trim().length() == 0)    //读取整个字符串,除去字符串多余的字符串
            return 0;
        while (str.charAt(start) == ' ' || str.charAt(start) == '0') {
            start++;
        }
        if (str.charAt(start) == '+' || str.charAt(start) == '-') {   //设置标志位,判断是正负?
            if (str.charAt(start) == '-') {
                neg = false;
                start++;
            } else
                start++;
        }
        while (start < str.length() && str.charAt(start) <= '9' && str.charAt(start) >= '0') {
            //     判断是否在0-9
            num = num * 10 + (str.charAt(start) - '0');
            start++;
            
            //由于这里num是long型,不必判断Integer.MAX_VALUE/10, 直接判断即可。
            if (neg && num > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            //
            else if (!neg && num * (-1) < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
        }
        num = neg ? num : num * (-1);   //三目运算
        return (int) num;
    }

态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5052868.html