Problem Solving/BOJ

[Silver 5] 11576번 Base Conversion

kmkunk 2022. 3. 25. 16:47
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        String[] ab = br.readLine().split(" ");
        Stack<String> stack = new Stack<>();
        int a = Integer.parseInt(ab[0]);
        int b = Integer.parseInt(ab[1]);
        int m = Integer.parseInt(br.readLine());
        String[] arr = br.readLine().split(" ");
        int n = 0;
        
        for(int i=0; i<m; i++) {
            n += Integer.parseInt(arr[i])*Math.pow(a, m-1-i);
        }

        while(n!=0) {
            stack.push(String.valueOf(n%b));
            n /= b;
        }
        
        while(!stack.isEmpty()) {
            sb.append(stack.pop()).append(" ");
        }
        
        System.out.println(sb);
    }
}