53. K진수 출력

zzzzwso·2023년 9월 18일
0

문제 설명

10진수 N이 입력되면 K진수로 변환하여 출력하는 프로그램을 작성하세요. 스택 자료구조를 사용하시기 바랍니다.

입력설명

첫 번째 줄에 10진수 N(10<=N<=1,000)과 K(2, 5, 8, 16)가 주어진다

출력설명

K진수를 출력한다.

stack 직접 구현

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int stack[100];
int top = -1;
void push(int x) {
	stack[++top] = x;
}

int pop() {
	return stack[top--];
}

int main()
{
	char str[20] = "0123456789ABCDEF";
	int n, k;
	cin >> n >> k;
	while (n > 0)
	{
		push(n % k);
		n = n / k;
	}
	while (top != -1)
	{
		cout << str[pop()];
	}
}

STL 이용

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

int main()
{
	char str[20] = "0123456789ABCDEF";
	int n, k;
	cin >> n >> k;
	stack<int> s;
	while (n > 0)
	{
		s.push(n % k);
		n = n / k;
	}
	while (!s.empty())
	{
		cout << str[s.top()];
		s.pop();
	}
}
profile
HI there

0개의 댓글