找零问题

Z国的货币系统包含面值1元、4元、16元、64元共计4种硬币,以及面值1024元的纸币。现在小Y使用1024元的纸币购买了一件价值为的商品,请问最少他会收到多少硬币?

解析1:数学方法。%为取余,/为取商

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int total = 1024;
        int cost = sc.nextInt();//总容量
        int a = (total - cost)/64;//12
        int b = ((total - cost)%64)/16;//3
        int c = (((total - cost)%64)%16)/4;
        int d = (((total - cost)%64)%16%4)/1;
        System.out.println(a+b+c+d);
    }
}

解析2:1,dp[i]为找零i所需的最小硬币数。2,初始化全部为i(最大值,找零1硬币的) 3,递推关系,dp[i]=min(dp[i],dp[i-num[j]]+1)

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int total = 1024;
        int cost = sc.nextInt();//总容量
        int change = total - cost;
        int[] dp = new int[change+1];
        for(int i = 1;i<=change;i++){
            dp[i] = i;
        }
        int[] num = {1,4,16,64};
        for(int i=1;i<=change;i++){
            for(int j=0;j<4;j++){
                if(i>=num[j]){//当找零要大于面额时
                     dp[i] = Math.min(dp[i],dp[i-num[j]]+1);
                } 
            }
        }
        System.out.print(dp[change]);
    }
}
全部评论

相关推荐

05-20 21:57
已编辑
门头沟学院 Java
喜欢吃卤蛋的悲伤蛙在...:建信融通没消息吧,我2说有实习挂简历不理了
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务