7進位制字串轉為10進位制的int型別數字(H3C筆試題)
阿新 • • 發佈:2018-12-31
【2011年華三通訊應屆生筆試題】題目:請寫一段將7進位制轉為10進位制的正整數的函式。
【思路】在Java API中有相關的函式,Integer.parsint(String str,int radix)。題目比較簡單。比如,”12”,即迴圈進行:result=0 result=result *7+1=1; result=result*7+2=9; 本題主要考察幾個異常情況和溢位情況,比如,超出Int範圍如何判斷。比如,某輪迴圈result為Integer.max/7,表明個位如果大於7進位制Integer.max的個位,則溢位;某輪迴圈result大於Integer.max/7,則不論個位是否大於7進位制Integer.max的個位,都溢位。
private static int parseInt(String str4, int radix) { /* 異常情況1:字串為null */ if (str4 == null) { throw new IllegalArgumentException("字串為null!"); } int length = str4.length(), offset = 0; /* 異常情況2:字串長度為0 */ if (length == 0) { throw new IllegalArgumentException("字串長度為0!"); } boolean negative = str4.charAt(offset) == '-'; if (negative) { throw new IllegalArgumentException("字串位負數!"); } int result = 0; char[] temp = str4.toCharArray(); while (offset < length) { char digit = temp[offset++]; int currentDigit = digit - '0'; /* 一位一位判斷,是否在0~7之間,否則為非法輸入 */ if (currentDigit < radix && currentDigit >= 0) { /* 2種溢位情況,第1種,當前的resut已經等於Integer.MAX_VALUE / 10,看個位數是否在範圍內 */ if (result == Integer.MAX_VALUE / radix && currentDigit > Integer.MAX_VALUE % radix) { throw new IllegalArgumentException("字串溢位!"); /* 2種溢位情況,第2種,當前的resut已經大於Integer.MAX_VALUE / 10,不論個位是什麼,都溢位 */ } else if (result > Integer.MAX_VALUE / radix) { throw new IllegalArgumentException("字串溢位!"); } /*關鍵部分*/ result = result * radix + currentDigit; } else { throw new IllegalArgumentException("字串字元不在0~"+radix+"!"); } } return result; }