Java實現八進制正整數轉化為十進制數


public class Main {
    public static void main(String[] args) {
        System.out.println(convert(23,2));
//        System.out.println(power(8,2));
    }

    private static int convert(int n, int i) {//n為輸入的八進制數,i為位數
        int temp[] = new int[i];
        int result = 0;
        for(int j=0;j < i;j++){
            temp[j] = (n/power(10,i-j-1))%power(10,1);
            result += temp[j]*power(8,i-j-1);
//            System.out.print(n + " " + temp[j] + " " + power(10,i-j-1) + " " + power(10,j) + "\n");
        }
//        System.out.println();
        return result;
    }

    private static int power(int i, int j) {
        int temp = 1;
        for(int k=0;k<j;k++){
            temp *= i;
        }
        return temp;
    }
}

 對於輸入的一個八位數,取得每一位的數字,例如:3254/1000%10 = 3(前面的/為取整,后面的%為取余數,注意為取得每位上的數字,取得整數部分后,然后取每個整數的個位數就可以了,也就是%10)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM