Q1. 거스름돈 구하는 문제

지불한 금액을 나타내는 파라미터1, 물건의 가격을 나타내는 파라미터2
이렇게 두 개의 파라미터를 받아 가장 적은 수의 지폐를 거슬러 주는 메소드를 만들어 주세요.
(단위는 50000, 10000, 5000, 1000 원입니다.)
   
 예) change(100000, 23000);
 출력결과 -> 50000원 지폐 : 1장
 10000원 지폐 : 2장 
 5000원 지폐 : 1장
 1000원 지폐 : 2장

 

 

 

A1-1. 내가 짰던 코드

public class MKY_ChangeMoney {

	public static void main(String[] args) {
		changeMoney(100000, 23000);
	}
	
	public static void changeMoney(int money, int price) {
		int cal = money - price;	// 거스름돈 구하기
		int cal2 = 0, cal3 = 0, cal4 = 0;	// 각 지폐별 변수 생성
		
		// 최소한의 지폐를 거슬러 주기 위해 5만원 단위부터 로직 구성
		if (cal>50000) {	// 거스름돈이 5만원보다 크다면 5만원 지폐를 거슬러줘야 한다.
			int bill = cal/50000;	// 5만원 몇 장이 필요한지 계산
			System.out.println("50000원 권 : " + bill + "장");
			cal2 = cal - (50000*bill);	// 거슬러줄 5만원 지폐를 제외하고 나머지 금액을 구한다.
		} 
		
		// 나머지도 같은 형식으로 진행됨
		// 거슬러 줄 지폐가 있다면 if문 안으로 들어가서 문장을 실행한다.
		if (cal2>10000) {
			int bill = cal2/10000;
			System.out.println("10000원 권 : " + bill + "장");
			cal3 = cal2 - (10000*bill);
		} 
		
		if (cal3>5000) {
			int bill = cal3/5000;
			System.out.println("5000원 권 : " + bill + "장");
			cal4 = cal3 - (5000*bill);
		} 
		
		if(cal4>1000) {
			int bill = cal4/1000;
			System.out.println("1000원 권 : " + bill + "장");
		}
	}
}

< console >----------------------------------------------------------------------------------
50000원 권 : 1장
10000원 권 : 2장
5000원 권 : 1장
1000원 권 : 2장

▶ 코드가 너무 길어져서 짜면서도 간단하게 할 방법이 있을 것 같았는데, 아래 다른 조원분이 해결해주셨다.

 

 

 

A1-2. 다른 조원이 짠 코드

package methodStudy;

public class JSH_ChangeMoney {

	public static void main(String[] args) {
		f1(100000, 23000);
	}
	
	 public static void f1(int x, int y){
	        int [] money = {50000, 10000, 5000, 1000};	// 지폐를 배열로 묶어줌
	        int div = 0, result = 0;
	       
	        result = x - y;
	        for(int i = 0; i<money.length; i++){	
	            div = result / money[i];	// 거슬러줘야하는 지폐 수
	            System.out.println(money[i] + "원 지폐: " + div + "장" );
	            result = result % money[i];	// 남은 거스름돈
	        }
	    }
}

▶ 각 단위의 지폐를 배열로 묶어주고 for 반복문을 돌림으로써 코드의 길이가 간결해졌다.

▶ %(나머지)로 남은 거스름돈을 알 수 있는 것도 생각지도 못했던 부분

 

 

 

A1-3. 다른 조원이 짠 코드2

public class CHH_ChangeMoney {

	public static void main(String[] args) {
		change(100000, 23000);
		
	}

	public static void change(int pay,int cost) {
		int changeMoney = pay - cost;
		
		int fifty_thousand = changeMoney / 50000;				
		int ten_thousand = (changeMoney % 50000) / 10000;	
		int five_thousand = (changeMoney % 10000) / 5000;	
		int one_thousand = (changeMoney % 5000) / 1000;		
		
		System.out.println("50000원 지폐 : " + fifty_thousand);
		System.out.println("10000원 지폐 : " + ten_thousand);
		System.out.println("5000원 지폐 : " + five_thousand);
		System.out.println("1000원 지폐 : " + one_thousand);
	}
}

▶ 나는 변수를 따로 설정하고 if문을 만들어 돌렸지만, 변수를 설정하면서 바로 로직이 가능하다.

▶ 로직을 짠 후 어떻게 더 간단하게 할 수 있을지 연구해봐야겠단 걸 많이 느낀 문제

728x90

+ Recent posts