【劍指offer-Java版】49把字符串轉換爲整數

字符串轉換爲整數 : atoi

可能的輸入:
1 帶符號數
2 無符號數
3 零
4 空指針
5 超出表示範圍 – 暫時僅僅是直接退出且設置最小 – 可以考慮此時拋個異常
6 非法輸入,比如並不是一個0-9或者+ -組成的字符串 – 對於非法輸入一律返回的是Integer.MIN_VALUE


    public class _Q49<T> {

    public long StrToInt(String str){
        if(str == null) return Long.MIN_VALUE; // 輸入非法還是拋異常提示或者約定
        if(str.length() == 0) return 0;

        // 判斷輸入字符串是否合法
        for (int i = 0; i < str.length(); i++) {
            if (!judge(str.charAt(i))) {
                return Long.MIN_VALUE;
            }
        }

        char chars[] = str.toCharArray();
        long result = 0;
        if(chars[0] == '-' || chars[0] == '+'){ // 有符號數
            result = trans(str.substring(1));
        }else{ // 無符號數
            result = trans(str);
        }

        if(result > 0 && chars[0] == '-') result = -result;

        return result;
    }

    private long trans(String str){
        if(str.length() == 0) return 0;

        long result = 0;
        for(int i=0; i<str.length(); i++){
            result = result*10 + (str.charAt(i)-'0');
            if(result > Long.MAX_VALUE){
                result = Long.MIN_VALUE;
                break;
            }
        }
        return result;
    }

    private boolean judge(char c){
        if(c == '-' || c == '+') return true;
        if(c >= '0' && c <= '9') return true;

        return false;
    }
    }

測試代碼:


    public class _Q49Test extends TestCase {

    _Q49<?> a2i = new _Q49();

    public void test(){
        String str1 = "123456";
        String str2 = "-123456";
        String str3 = "-6";
        String str4 = "-";
        String str5 = "+1";
        String str6 = "+abc";
        String str7 = null;

        System.out.println(a2i.StrToInt(str1));
        System.out.println(a2i.StrToInt(str2));
        System.out.println(a2i.StrToInt(str3));
        System.out.println(a2i.StrToInt(str4));
        System.out.println(a2i.StrToInt(str5));
        System.out.println(a2i.StrToInt(str6));
        System.out.println(a2i.StrToInt(str7));
    }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章