美文网首页
lint0241 0054 String to Integer

lint0241 0054 String to Integer

作者: 日光降临 | 来源:发表于2019-02-07 20:22 被阅读0次

0241 String to Integer
0054 String to Integer (atoi)

lo ... hi
1 2 3

方法一:
100% test cases passedTotal runtime 205 ms
Your submission beats 40.40% Submissions!

public class Solution {
    public int stringToInteger(String str) {
        int lo=0;
        int hi=str.length();
        int sign=1;
        int sum=0;
        if(str.charAt(lo) == '-'){
            sign=-1;
            lo++;
        }
        while(hi>lo){
            sum=sum*10+str.charAt(lo)-'0';
            lo++;
        }
        return sum*sign;
    }
}

0054这是有点崩溃,另外lintcode的评测系统是真的很烂

public class Solution {
    public int atoi(String str) {
        int lo=0;
        int hi=str.length();
        int sign=1;
        long val=0L;
        if(hi==0)
        return 0;
        for(;isspace(str.charAt(lo));lo++)
            ;
        if(str.charAt(lo) == '-'){
            lo++;
            sign=-1;
        }else if(str.charAt(lo)=='+')
            lo++;

        for(;lo<hi;lo++){
            if(str.charAt(lo)<'0' || str.charAt(lo)>'9')
                break;
            val=10*val +(str.charAt(lo)-'0');
            if(val > Integer.MAX_VALUE)
                break;
        }
            
        if(val*sign>=Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if(val*sign<=Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        
        return (int)(val*sign);
    }
    private boolean isspace(char ch){
        return (ch==' ' || ch=='\n' || ch=='\t');
    }
}

相关文章

网友评论

      本文标题:lint0241 0054 String to Integer

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