본문 바로가기
공부하자/알고리즘

[백준] 5585번 거스름돈 C, java

by snbrin 2022. 1. 4.

https://www.acmicpc.net/problem/5585

 

5585번: 거스름돈

타로는 자주 JOI잡화점에서 물건을 산다. JOI잡화점에는 잔돈으로 500엔, 100엔, 50엔, 10엔, 5엔, 1엔이 충분히 있고, 언제나 거스름돈 개수가 가장 적게 잔돈을 준다. 타로가 JOI잡화점에서 물건을 사

www.acmicpc.net

 

C 풀이1

#include <stdio.h>

int main() {

	int pay;
	int one = 1000;
	int left;
	int count = 0;

	scanf("%d", &pay);

	left = one - pay;

	while (left != 0) {
		if (left >= 500) {
			left -= 500;
			count++;
		}
		else if (left >= 100) {
			left -= 100;
			count++;
		}
		else if (left >= 50) {
			left -= 50;
			count++;
		}
		else if (left >= 10) {
			left -= 10;
			count++;
		}
		else if (left >= 5) {
			left -= 5;
			count++;
		}
		else {
			left -= 1;
			count++;
		}
	}

	printf("%d", count);

	return 0;
}

 

C 풀이2

#include <stdio.h>

int main() {

	int pay;
	int one = 1000;
	int left;
	int count = 0;

	scanf("%d", &pay);

	left = one - pay;

	for (; left >= 500;) {
			left = left - 500;
			count++;
	}
	for (; left >= 100;) {
			left -= 100;
			count++;
	}
	for (; left >= 50;) {
		left -= 50;
		count++;
	}
	for (; left >= 10;) {
		left -= 10;
		count++;
	}
	for(; left >= 5;) {
		left -= 5;
		count++;
	}
	for (; left >= 1;) {
		left -= 1;
		count++;
	}
	

	printf("%d", count);

	return 0;
}

 

java

package javastd1;

import java.util.Scanner;

public class bj5585 {
	
	public static void main(String[] args) {
		
	Scanner sc = new Scanner(System.in);
	
	int one = 1000;
	int left=0;
	int cnt=0;
	
	int pay = sc.nextInt();
	
	left = one - pay;
	
	while(left != 0) {
		if (left >= 500) {
			left -= 500;
			cnt++;
		}
		else if (left >= 100) {
			left -= 100;
			cnt++;
		}
		else if (left >= 50) {
			left -= 50;
			cnt++;
		}
		else if (left >= 10) {
			left -= 10;
			cnt++;
		}
		else if (left >= 5) {
			left -= 5;
			cnt++;
		}
		else {
			left -= 1;
			cnt++;
		}
	}
	
	
	System.out.println(cnt);
	sc.close();
	
	}
}