자료구조와 알고리듬 With Java/[Study] BAEKJOON 프로그래머스 CodeUp LeetCode

Code up 1714 숫자 거꾸로 출력하기

계란💕 2022. 3. 13. 01:50

 

  Ex) Stack을 이용해서 숫자 거꾸로 출력하기

<hide/>
package D220310;

import java.util.Scanner;
import java.math.*;
interface IStackable17141{
	boolean empty();
	int peek();
	void pop();
	void push(int nData);
	// int search(int nData);
}

public  class ReversePrint  implements IStackable17141{
	private int [] mnArray;
	private int mnCapacity;
	private int mnTop;
	
	public ReversePrint(int nCapacity) {
		mnArray = new int[nCapacity];
		mnCapacity = nCapacity;
		mnTop = 0;
	}

	public boolean empty() {
		return (0 == mnTop);
	}
	
	public void push(int nData) {
		if( true == full()) {
			System.out.println("Stack Overflow!");
			return;
		}
		mnArray[mnTop++] = nData;
	}
	
	public void pop(){
		if( true == empty()) {
			System.out.println("Stack Underflow!");
			return;
		}
		--mnTop;
	}
	
	public int peek() {
		if(true == empty()) {
			System.out.println("Stack Underflow!");
			return -1;
		}
		return mnArray[mnTop-1];
	}
	
	public boolean full() {
		return (mnCapacity == mnTop);
	
	}

		public static int Count(int n) {	// 자릿수 구하는 함수 Count
		
			int count = 0;
			for(int i = 0; ; ++i ) {
	
				if( n != 0) {
				++count;	
				}
				if( n == 0 ) {
				break;
				}
				n /= 10;	
			}
		return count;
		}
	
		public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		
		int n = scan.nextInt();
		
		if(n != 0) {

			int  nCapacity  = Count(n);	//	 입력된 수의 자릿수 구하는 count함수
		
			ReversePrint st = new ReversePrint(nCapacity);
			ReversePrint st2 = new ReversePrint(nCapacity);

			for(int i = 0; ; ++i ) {  //  스택 st에 push를 이용해서 일의 자리수부터 차례대로 스택에 넣는다.
		
				st.push(n % 10);
				n = n /10;
				
				if(n == 0) {
					break;
				}
			}
			
			while(false == st.empty()) {
				st.peek();
				st2.push(st.peek());
				st.pop();			
			}
			
			while(false == st2.empty()) 	{
				System.out.printf("%d",st2.peek());
				st2.pop();
			}
		}else {						//  입력되는 값이 0인 경우를 위해 작성
			System.out.printf("%d", n);

		}
	}		
}

 

 

    Note) 실행결과

  - stack의 원리를 적용해서 peek(), pop(), push(), empty()를 구현한다.

  - 0이 입력되는 경우를 고려해서 뒷 부분 코드를 추가했다.

  - 출력 상으로는 문제가 없는데 수정이 조금 필요하다.