十進制中的數位排列是這樣的…… 萬 千 百 十 個 十分 百分 千分……
R進制中的數位排列是這樣的……R^4 R^3R^2 R^1 R^0 R^-1 R^-2 R^-3……
所以任意進制轉為10進制直接就按權展開就行
即 十進制
9876=9×10^3+8×10^2+7×10^1+6×10^0 = 9000 + 800 + 70 + 6 = 9876
二進制 1011 = 1×2^3+0×2^2+1×2^1+1×2^0 = 8+2+1 = 11
所以直接從最后一位開始,加上每一位的10進制,最終的和就是待轉換數的十進制
1 import java.util.Scanner; 2 3 public class Change { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Scanner cin = new Scanner(System.in); 8 System.out.print("輸入待轉換的數和其進制:"); 9 int OldNum = cin.nextInt();//待轉換成10進制的數 10 int x = cin.nextInt();//待轉換數的進制 11 int num = x2ten(OldNum, x); 12 System.out.println(num); 13 } 14 public static int x2ten(int n, int x) { 15 int num = 0; 16 int k = 1; 17 while(n!=0) { 18 int m = n % 10;//取最后一位數 19 num += m * k; 20 n = n / 10; 21 k *= x; 22 } 23 return num; 24 } 25 }