본문 바로가기

알고리즘/문제 풀이

SW D2 1970 쉬운 거스름돈

SW Expert Academy

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

1. 내 코드

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;


class Solution
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<>();

        for (int test_case = 1; test_case <= T; test_case++) {
            int N = sc.nextInt();
            divide(list, N, 50000);
            if(list.size()<8){
                for (int i = list.size(); i < 8; i++) { 
                    // 만약 거스름돈이 5만원 만원 오천원등 상위 타선에서 끝났다면, 그 뒤는 다 0으로 채워라 
                    list.add(0);
                }
            }
            System.out.println("#"+ test_case);
            list.stream().forEach(x -> System.out.print(x + " ")); // 출력
            System.out.println();
            list.clear();
        }
    }

    static int divide (ArrayList<Integer> list, int N, int money) {
        list.add(N/money); // 나누었을 때 값의 맨 첫 글자가 1이냐 2냐에 따라서 들어가는 money의 값이 달라짐.
        if(String.valueOf(money/5).charAt(0) == '1'){  
            if(N%money>=10) return divide(list, N%money, money/5);
            else return 0;
        } else if (String.valueOf(money/5).charAt(0) == '2') {
            if(N%money>=10) return divide(list, N%money, money/2);
            else return 0;
        }else {
            return -1;
        }

    }

}

2. 다른 사람의 코드

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
 
public class Solution {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
         
        int T = sc.nextInt();
         
        // money를 나눌 값들을 미리 배열로 나열
        int[] m = {50000, 10000, 5000, 1000, 500, 100, 50, 10};
         
        for(int tc=0; tc<T; tc++) {
            int money = sc.nextInt();
            
            // 거스름돈이 들어가는 그릇
            int[] change = new int[8];
             
            System.out.println("#"+(tc+1));
            for(int i=0; i<m.length; i++) {
                if(money/m[i]>0) {
                
                	//돈을 5만원~10원 순으로 나눠서 몫을 거스름돈 그릇에 집어넣는다
                    change[i] = money/m[i]; 
                    
                    // money는 m[i]로 거스른 뒤 남은 잔액으로 최신화 
                    money%= m[i];
                }
                System.out.print(change[i]+" ");
            }
     
            System.out.println();
        }
    }
}