1번 문제   

 

 


 

    내가 풀이한 답   

 

 Stack 자료구조를 사용하였다. 이 문제를 풀 때 주의해야 할 점은 두 가지가 있는데 첫 번째는 while문에서 종료 조건문을 n이 k진수보다 작을 때 종료해야 한다는 점과 16진수에서 10이상 15이하의 숫자는 A~F로 표현된다는 점이다. 

//#include <bits/stdc++.h>
#include <iostream>
#include <stack>
using namespace std;

int main() {
	//freopen("input.txt", "rt", stdin);
	
	int n, k;
	char a[6] = {'A', 'B', 'C', 'D', 'E', 'F'};
	cin >> n >> k;
	stack<int> s;
	
	while(n>k-1){
		s.push(n%k);
		n = n/k;
 		if(n<k) {
 			s.push(n);	
		}
	}
	
	
	while(!s.empty()){
		if(k==16) {
			if(s.top()>=10) {
				cout << a[s.top()-10];
				s.pop();
			}
			cout << s.top();
			s.pop();	
		}
		else {
			cout << s.top();
			s.pop();	
		}	
	}
	
	return 0;
}

 

 결과는 통과하였다.

 

 



    사이트의 답안   

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int stack[100], top=-1;

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

int main(){
	freopen("input.txt", "rt", stdin);
	int n, k;
	char str[20]="0123456789ABCDEF";
	scanf("%d %d", &n, &k);
	while(n>0){
		push(n%k);
		n=n/k;
	}
	while(top!=-1){
		printf("%c", str[pop()]);
	}	
	return 0;
}




#include<stdio.h>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;		
int main(){
	freopen("input.txt", "rt", stdin);
	int n, k;
	stack<int> s;
	char str[20]="0123456789ABCDEF";
	scanf("%d %d", &n, &k);
	while(n>0){
		s.push(n%k);
		n=n/k;
	}
	while(!s.empty()){
		printf("%c", str[s.top()]);
		s.pop();
	}	
	return 0;
}

'알고리즘 & 자료구조 > 스택, 큐' 카테고리의 다른 글

4. 프린터 큐(Queue)  (0) 2020.11.01
3. 요세푸스 문제 0(Queue)  (0) 2020.10.31
2. 카드2(Queue)  (0) 2020.10.31