/**
* 有1,5,10,50,100,500元的硬币各C1,C5,C10,C50,C100,C500枚
* 现在要用这些硬币来支付A元,最少需要多少枚硬币?
* 假定本题至少存在一种解决方案
* 思路,贪心算法
* @author haofan.whf
* @version $Id: Coin.java, v 0.1 2018年06月12日 下午5:13 haofan.whf Exp $
*/
public class Coin {
public void solution(int A, int C1, int C5, int C10, int C50, int C100, int C500){
int nc500 = 0;
if(A / 500 > 0){
nc500 = A / 500 > C500 ? C500 : A / 500;
System.out.println("需要500元硬币" + nc500 + "枚");
A = A - nc500 * 500;
}
int nc100 = 0;
if(A / 100 > 0){
nc100 = A / 100 > C100 ? C100 : A / 100;
System.out.println("需要100元硬币" + nc100 + "枚");
A = A - nc100 * 100;
}
int nc50 = 0;
if(A / 50 > 0){
nc50 = A / 50 > C50 ? C50 : A / 50;
System.out.println("需要50元硬币" + nc50 + "枚");
A = A - nc50 * 50;
}
int nc10 = 0;
if(A / 10 > 0){
nc10 = A / 10 > C10 ? C10 : A / 10;
System.out.println("需要10元硬币" + nc10 + "枚");
A = A - nc10 * 10;
}
int nc5 = 0;
if(A / 5 > 0){
nc5 = A / 5 > C5 ? C5 : A / 5;
System.out.println("需要5元硬币" + nc5 + "枚");
A = A - nc5 * 5;
}
int nc1 = A;
System.out.println("需要1元硬币" + nc1 + "枚");
System.out.println("共需要硬币" + (nc1 + nc5 + nc10 + nc50 + nc100 + nc500) + "枚");
}
}
硬币问题
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。