劍指offer-把字符串轉換成整數

題目描述

將一個字符串轉換成一個整數(實現Integer.valueOf(string)的功能,可是string不符合數字要求時返回0),要求不能使用字符串轉換整數的庫函數。 數值爲0或者字符串不是一個合法的數值則返回0。
輸入一個字符串,包括數字字母符號,能夠爲空
若是是合法的數值表達則返回該數字,不然返回0
+2147483647      2147483647
1a33     0
    public int StrToInt(String str) {
        if(str==null||str.length()==0||str.equals("0")){
            return 0;
        }
        int i=0;
        boolean isPositive = true;
        if(str.charAt(0)=='+'){
            isPositive =true;
            i++;
        }
        else if(str.charAt(0)=='-'){
            isPositive =false;
            i++;
        }
        int re =0;
        for(;i<str.length();i++){
            char ch =str.charAt(i);
            if(ch<'0'||ch>'9'){
                return 0;
            }
            re = re*10+ch-'0';
        }
        return isPositive?re :-re;
        
    }
相關文章
相關標籤/搜索