스터디/알고리즘

[알고리즘][C++] K진수 출력 (stack 자료구조)

y00&z1 2022. 8. 15. 13:07

stack 자료구조 : 

int stack[SIZE]
top=-1

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

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

 

 

input : 11 2 

11 를 2로 나눈 나머지를 push !

2	11	(1)
2	5	(1)
2	2	(0)
2	1	(1) <-top

 

 

 

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

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

int main(){ 
	//freopen("input.txt", "rt", stdin);
	int n, k; 
	stack<int> s;
	char str[20]="0123456789ABCDEF";//16진수때문에 !  
	
	scanf("%d %d", &n, &k);
	
	while(n>0){
		s.push(n%k);
		n=n/k;
	}
	
	while(!s.empty()){ //top!=-1
		printf("%c", str[s.top()]);
		s.pop();//주의!! 반드시 필요
	}
	return 0;
}