演算法與資料結構面試題(23)-將字串轉化為整形__JAVA

來源:互聯網
上載者:User
題目


輸入一個表示整數的字串,把該字串轉換成整數並輸出。 例如輸入字串"345",則輸出整數 345。

個人理解


這個面試題不太 涉及演算法和資料結構,主要考察你的編程習慣,有沒有意識去做一些驗證,對輸入的校正。小問題驗證大方面。乘機我們來看看java api中對這個問題的處理


代碼


public static int parseInt(String s) throws NumberFormatException {        return parseInt(s,10);    }public static int parseInt(String s, int radix)                throws NumberFormatException    {        /*         * WARNING: This method may be invoked early during VM initialization         * before IntegerCache is initialized. Care must be taken to not use         * the valueOf method.         */        if (s == null) {            throw new NumberFormatException("null");        }        if (radix < Character.MIN_RADIX) {            throw new NumberFormatException("radix " + radix +                                            " less than Character.MIN_RADIX");        }        if (radix > Character.MAX_RADIX) {            throw new NumberFormatException("radix " + radix +                                            " greater than Character.MAX_RADIX");        }        int result = 0;        boolean negative = false;        int i = 0, len = s.length();        int limit = -Integer.MAX_VALUE;        int multmin;        int digit;        if (len > 0) {            char firstChar = s.charAt(0);            if (firstChar < '0') { // Possible leading "+" or "-"                if (firstChar == '-') {                    negative = true;                    limit = Integer.MIN_VALUE;                } else if (firstChar != '+')                    throw NumberFormatException.forInputString(s);                if (len == 1) // Cannot have lone "+" or "-"                    throw NumberFormatException.forInputString(s);                i++;            }            multmin = limit / radix;            while (i < len) {                // Accumulating negatively avoids surprises near MAX_VALUE                digit = Character.digit(s.charAt(i++),radix);                if (digit < 0) {                    throw NumberFormatException.forInputString(s);                }                if (result < multmin) {                    throw NumberFormatException.forInputString(s);                }                result *= radix;                if (result < limit + digit) {                    throw NumberFormatException.forInputString(s);                }                result -= digit;            }        } else {            throw NumberFormatException.forInputString(s);        }        return negative ? result : -result;    }

先瞭解下面的知識,對理解上面的代碼有好處。


在Java中>、>>、>>>三者的區別在java中:>表示大於,如:if(a>b)...結果是boolean類型>>表示右移,如:int i=15; i>>2的結果是3,移出的部分將被拋棄。轉為二進位的形式可能更好理解,0000 1111(15)右移2位的結果是0000 0011(3),0001 1010(18)右移3位的結果是0000 0011(3)。j>>>i 與 j/(int)(Math.pow(2,i))的結果相同,其中i和j是整形。


我們一步一步的debug, 來看看處理代碼


1.進入


public static void main(String[] args){        //10進位        Integer.parseInt("235",10);    }

上面是入口函數。



傳入的字串為"235"。進入方法體後,第一步是判斷是否為null。如果為空白,拋出異常。然後是判斷基數是否在可允許範圍內[2-32],我們傳入的是10。在可允許內


2.初始化操作




result:我們需要的結果

negative:是否為負數。預設為false

i:遊標,指向字串當前的索引,遍曆字串中字元。

len:字串大小

limit:整形的最大值的負值。比整形的最小值-2147483648大1.

multmin:

digit:儲存字元經過轉化後的整形值


3.判斷字串第一個字元是否是符號位(+,-)


char firstChar = s.charAt(0);            if (firstChar < '0') { // Possible leading "+" or "-"                if (firstChar == '-') {                    negative = true;                    limit = Integer.MIN_VALUE;                } else if (firstChar != '+')                    throw NumberFormatException.forInputString(s);                if (len == 1) // Cannot have lone "+" or "-"                    throw NumberFormatException.forInputString(s);                i++;            }

如果第一個字元為'-',將negative的值設定為true,將limit設定為整形最小值:Integer.MIN_VALUE。

如果第一個字元不為‘-’,然後再附加判斷一下是否為加號,如果不是加號,拋出異常

再然後判斷一下字串的大小是否為1,如果為1,不符合要求,因為只有符號位肯定是不複製整數的定義的。

最後字串遍曆的遊標自增1。表示遍曆要從第二個字元開始,因為第一個字元我們已經判斷是符號位。


4.遍曆字串




首先我們將multmin的值賦上值,賦上值有啥作用?,它為啥要除以基準值。暫時還不清楚。先放著吧。


multmin = limit / radix;

然後開始迴圈獲得字串中每一個字元的值


while (i < len) {                // Accumulating negatively avoids surprises near MAX_VALUE                digit = Character.digit(s.charAt(i++),radix);                if (digit < 0) {                    throw NumberFormatException.forInputString(s);                }                if (result < multmin) {                    throw NumberFormatException.forInputString(s);                }                result *= radix;                if (result < limit + digit) {                    throw NumberFormatException.forInputString(s);                }                result -= digit;            }

首先瞭解第一個語句塊


digit = Character.digit(s.charAt(i++),radix);



可以看見字元'2'的ascii碼為50,我們對照一下的確是50。




上面的方法中,首先將字元轉換成ascii碼,然後再調用覆蓋函數digit。



這個時候會發現傳進來的是50,也就是‘2’的ascii碼值。進入該函數後,首先通過CharacterData.of方法來得到該字元屬於哪個編碼集範圍內。


static final CharacterData of(int ch) {        if (ch >>> 8 == 0) {     // fast-path            return CharacterDataLatin1.instance;        } else {            switch(ch >>> 16) {  //plane 00-16            case(0):                return CharacterData00.instance;            case(1):                return CharacterData01.instance;            case(2):                return CharacterData02.instance;            case(14):                return CharacterData0E.instance;            case(15):   // Private Use            case(16):   // Private Use                return CharacterDataPrivateUse.instance;            default:                return CharacterDataUndefined.instance;            }        }    }

首先ch>>>8位元運算。意思是ch/2的8次方法。主要是判斷是否可以用拉丁字元範圍內的值表示。很顯然我們可以用拉丁字元編碼集中字元範圍來表示。所以方法返回。


進入CharacterDataLatin1類的digit方法


int digit(int ch, int radix) {        int value = -1;        if (radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX) {            int val = getProperties(ch);            int kind = val & 0x1F;            if (kind == Character.DECIMAL_DIGIT_NUMBER) {                value = ch + ((val & 0x3E0) >> 5) & 0x1F;            }            else if ((val & 0xC00) == 0x00000C00) {                // Java supradecimal digit                value = (ch + ((val & 0x3E0) >> 5) & 0x1F) + 10;            }        }        return (value < radix) ? value : -1;    }

首先判斷基準值是不是符合要求,這個已經比對過了,無需再說了。然後進入getProperties方法。


 int getProperties(int ch) {        char offset = (char)ch;        int props = A[offset];        return props;    }

返回了一個很大的數,為unicode值;暫且理解為unicode碼轉化為10進位後的數,然後與16進位數0x1F做 位與運算。




為何要做位與運算,先來看看位於運算是什麼。


& 是按二進位的按位與,即 1 & 1 = 1   1 & 0 = 0   3 & 1 → 11(二進位) & 1 = 1

上面的0x1F表示的是位元為:00011111。如果按照上面的運演算法則,那麼只有後5位為1的位才能被保留下來。


10進位數402667017轉化為位元為


11000000000000011011000001001

那麼後5位為01001&11111 = 01001;所以我們知道其實就是取後5位的數二進位碼,其他位置全部改為0。得到的10進位數就是9。


if (kind == Character.DECIMAL_DIGIT_NUMBER) 

根據這句代碼我們知道,和0x1F位於是要計算出其所處的類別。9代表的是Unicode 規範中的常規類別“Nd”。然後再做如下的位元運算


value = ch + ((val & 0x3E0) >> 5) & 0x1F;

0x3E0 = 10 1111 0000 &10 0000 1001 = 10 0000 0000  然後向右位移5位得到10 000由於優先順序+大於&。所以先進行相加運算50+16 = 66 (1000010)

1000010&11111 = 10 =,10進位就為2;所以最後的value = 2;


所以方法返回到Integer.parseInt中,得到digit = 2;


while (i < len) {                // Accumulating negatively avoids surprises near MAX_VALUE                digit = Character.digit(s.charAt(i++),radix);                if (digit < 0) {                    throw NumberFormatException.forInputString(s);                }                if (result < multmin) {                    throw NumberFormatException.forInputString(s);                }                result *= radix;                if (result < limit + digit) {                    throw NumberFormatException.forInputString(s);                }                result -= digit;            }

然後是2個if判斷。很容易理解:不能為負數,因為此時計算的位元沒有符號可言。

後面一個判斷result<multmin是什麼意思呢。因為result即將*10。如果result<multmin,那麼再*10的話肯定超出最小的範圍。這個地方為什麼不能直接先乘後比較,先乘後比較就沒有意義了,如果超出了範圍,已經報錯了,後面的判斷也就不會執行。接下來的一句的判斷同樣是這個道理,因為result即將與digit相減,但是相減的前提是它不能越界。所以有個預先判斷。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.