進制轉換

十進制轉八進制

最近水題的時候水到一個題目,題目以下:java

思路很簡單,就是將對應的數字取餘再除以8,如此往復。git

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextInt()) {
            decimalToOctal(scanner.nextInt());
        }
    }

    private static void decimalToOctal(int num) {

        int radix = 8; //8進制
        int result=0;
        int base = 1;
        while(num!=0)    
        {
            int temp = num%radix;
            temp = temp*base;
            base *= 10;
            result += temp;
            num/=radix;
        }
        System.out.println(result);
    }

}

通用解法

上面這種解法並不通用,只能轉換爲8進制,並且沒法應付num是負數的狀況好比-8, 其八進制根據原碼、補碼的規則應該是FFFFFFF8。後來想起java.lang.Integer中也有進制轉換的函數,想看看JDK是如何實現進制轉換的。 就這樣發現了一個通用解法。app

 

 /**
     * All possible chars for representing a number as a String
     */
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

    /**
     * Returns a string representation of the first argument in the
     * radix specified by the second argument.
     *
     * <p>If the radix is smaller than {@code Character.MIN_RADIX}
     * or larger than {@code Character.MAX_RADIX}, then the radix
     * {@code 10} is used instead.
     *
     * <p>If the first argument is negative, the first element of the
     * result is the ASCII minus character {@code '-'}
     * ({@code '\u005Cu002D'}). If the first argument is not
     * negative, no sign character appears in the result.
     *
     * <p>The remaining characters of the result represent the magnitude
     * of the first argument. If the magnitude is zero, it is
     * represented by a single zero character {@code '0'}
     * ({@code '\u005Cu0030'}); otherwise, the first character of
     * the representation of the magnitude will not be the zero
     * character.  The following ASCII characters are used as digits:
     *
     * <blockquote>
     *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
     * </blockquote>
     *
     * These are {@code '\u005Cu0030'} through
     * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
     * {@code '\u005Cu007A'}. If {@code radix} is
     * <var>N</var>, then the first <var>N</var> of these characters
     * are used as radix-<var>N</var> digits in the order shown. Thus,
     * the digits for hexadecimal (radix 16) are
     * {@code 0123456789abcdef}. If uppercase letters are
     * desired, the {@link java.lang.String#toUpperCase()} method may
     * be called on the result:
     *
     * <blockquote>
     *  {@code Integer.toString(n, 16).toUpperCase()}
     * </blockquote>
     *
     * @param   i       an integer to be converted to a string.
     * @param   radix   the radix to use in the string representation.
     * @return  a string representation of the argument in the specified radix.
     * @see     java.lang.Character#MAX_RADIX
     * @see     java.lang.Character#MIN_RADIX
     */
    public static String toString(int i, int radix) {
        // 參數驗證,若是不和要求則轉爲十進制 //
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        // 若是是轉爲十進制就直接toString() //
        /* Use the faster version */
        if (radix == 10) {
            return toString(i);
        }

        // 開始轉換 //
        char buf[] = new char[33]; //用於構造最後的結果字符串
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) { //將正數轉爲負數,方便後面正負數統一處理
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }
相關文章
相關標籤/搜索