美文网首页
leetcode 8--java实现atoi

leetcode 8--java实现atoi

作者: Ariana不会哭 | 来源:发表于2018-12-14 01:38 被阅读0次

这个题的确挺恶心,在leetcode上面是medium。leetcodde有一道题判断字符串是否为数字(包含e+小数点+幂次。。。)这个题的要求不是很多,以下是题目要求:


图片.png

这次题目和以往的增加整数集范围,当然之前的空格也可以用trim()进行处理,这个是字符串处理的基本方法,这就不说了,下面是题目给出的用例:


图片.png
class Solution {
    //my
    public int myAtoi2(String str) {
        if(str.isEmpty())
            return 0;
        Boolean positive=true;
        int base=0,n=str.length(),i=0;
        while(i<n&& str.charAt(i)==' ')
            i++;
        if(i<n&& (str.charAt(i)=='+'|| str.charAt(i)=='-'))//********
            positive=(str.charAt(i++)=='+')? positive:false;
        while(i<n&& str.charAt(i)>='0'&& str.charAt(i)<='9'){
            if(base>Integer.MAX_VALUE/10 || 
               (base==Integer.MAX_VALUE/10 &&str.charAt(i)-'0'>7))
                return (positive==true)? Integer.MAX_VALUE:Integer.MIN_VALUE;
            base=10*base+(str.charAt(i++)-'0');
        }
        return (positive==true)? base:base*(-1);
    }
}


public class lc8 {
    public static void main(String arg[]) {
        Solution test=new Solution();
        
        int a=test.myAtoi2("2147483646");
        System.out.println("Hello World");

    }
}

关于代码的答疑时间:

  1. base==Integer.MAX_VALUE/10 &&str.charAt(i)-'0'>7
    最大的数是:4294967296
    最小的书是:-2147483648

相关文章

网友评论

      本文标题:leetcode 8--java实现atoi

      本文链接:https://www.haomeiwen.com/subject/dbaihqtx.html