黑发不知勤学早,白首方悔读书迟。
代码:输入十进制数和要转换为几进制,回车结束。
//先入后出
import java.util.Scanner;
public class DecimalSystemConversion {
private static Scanner in;
public static void main(String[] args) {
System.out.println("Please enter a decimal number and you want to convert it to N-ary.");
in = new Scanner(System.in);
int n = in.nextInt(); // 存放十进制数
int m = in.nextInt(); // 存放转换进制数
DecimalSystemConversion dsc = new DecimalSystemConversion();
while (dsc.exchange(n, m)) {
System.out.println("Please enter a decimal number and you want to convert it to N-ary.");
n = in.nextInt(); // 存放十进制数
m = in.nextInt(); // 存放转换进制数
}
}
public boolean exchange(int num, int n) {
if (n > num) {
System.out.println("Don't kid,buddy,fatal error!");
return true;
}
int[] s = new int[10];// 定义一个顺序栈
int top, x;
top = -1;// 初始化栈
while (num != 0) {// 入栈 num = 100, n = 8
s[++top] = num % n;// 余数入栈 s[0] = 4, s[1] = 4, s[2] = 1
//执行完 top = 2
num = num / n;// 商作为被除数继续 num = 12, num = 1, num = 0
}
while (top != -1) {
x = s[top--]; // 出栈 x = s[2], x = s[1], x = s[0]
System.out.print(x);
}
return false;
}
}