Loading

第十九题、数制转换(难度系数75)

数制转换
标准输入输出
题目描述:
数制转换。(要求采用栈实现,练习进栈入栈函数的编写)
输入:
输入的第一行包含两个数,n,d
n表示要转换的数的个数
d表示要转换成的进制数
接下来是n个十进制数
输出:
对每一测试用例,用一行输出数制转换后的结果
输入样例:

2 8
123
213

输出样例:

173
325

参考一:


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int d = sc.nextInt();
        while (n-- > 0) {
            Stack<Integer> st = new Stack<>();
            int x = sc.nextInt();
            while (x > 0) {
                st.push(x % d);
                x /= d;
            }
            if (st.size() == 0) {
                System.out.println(0);
            } else {
                while (st.size() > 0) {
                    System.out.print(st.pop());
                }
                System.out.println();
            }
        }
    }
}

参考二:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int d = sc.nextInt();
        while (n-- > 0) {
            int a = sc.nextInt();
            System.out.println(Integer.toString(a, d));
        }
    }
}
posted @ 2023-02-19 20:10  qing影  阅读(25)  评论(0)    收藏  举报  来源