题目描述

利用栈类,实现将一个十进制整数转化为二至九进制之间的任一进制输出。函数原型void Convert(int num,int d),将十进制num转换为d进制,在函数体内实现输出即可。
若num为正整数,则算法规则如下:
循环(直至num为0)
{ 将num%d压栈;
num/=d;
}
循环(栈非空)
{
栈顶元素弹栈,输出(进制的高位)
}
要求程序能够处理正、负整数(含0)

输入

输入:6 2
输出:110
输入:90 8
输出:132

输出

样例输入

6 2

样例输出

110

提示

来源

提交

  1. import java.util.Scanner;
  2. class Node {
  3. public Object data;
  4. public Node next;
  5. public Node() {
  6. this(null,null);
  7. }
  8. public Node(Object data) {
  9. this(data,null);
  10. }
  11. public Node(Object data, Node next) {
  12. this.data = data;
  13. this.next = next;
  14. }
  15. }
  16. class LinkStack{
  17. Node top;
  18. public LinkStack() {
  19. top = null;
  20. }
  21. public void push(Object x){
  22. top = new Node(x,top);
  23. }
  24. public Object pop() throws Exception {
  25. if(isEmpty()){
  26. throw new Exception("Downflow");
  27. }else {
  28. Node p = top;
  29. top = top.next;
  30. return p.data;
  31. }
  32. }
  33. public Object getTop() throws Exception {
  34. if(isEmpty()){
  35. throw new Exception("Downflow");
  36. }else {
  37. return top.data;
  38. }
  39. }
  40. public boolean isEmpty(){
  41. return top==null;
  42. }
  43. }
  44. public class Main {
  45. public static void main(String[] args) {
  46. Scanner scanner = new Scanner(System.in);
  47. int num1 = scanner.nextInt();
  48. int num2 = scanner.nextInt();
  49. new Main().Convert(num1,num2);
  50. }
  51. public void Convert(int num,int d){
  52. LinkStack l = new LinkStack();
  53. int shang;
  54. int yu;
  55. while(num!=0){
  56. l.push(num % d);
  57. num/=d;
  58. }
  59. while(!l.isEmpty()){
  60. try {
  61. System.out.print(l.pop());
  62. } catch (Exception e) {
  63. // TODO Auto-generated catch block
  64. e.printStackTrace();
  65. }
  66. }
  67. }
  68. }