• SICP 实例 ExchangeMoney


    (define (first-denomination kinds-of-coin)
    (cond ((= kinds-of-coin 1) 1)
    ((= kinds-of-coin 2) 5)
    ((= kinds-of-coin 3) 10)
    ((= kinds-of-coin 4) 25)
    ((= kinds-of-coin 5) 50)))

    (define (cc amount kinds-of-coin)
    (cond ((= amount 0) 1)
    ((or (< amount 0) (= kinds-of-coin 0)) 0)
    (else (+ (cc amount
    (- kinds-of-coin 1))
    (cc (- amount
    (first-denomination kinds-of-coin))
    kinds-of-coin)))))

    (define (count-change amount)
    (cc amount 5))

    (count-change 100)

    Java实现:

    /**
    * Created by Ramble on 2017/11/22.
    */
    public class ExchangeMoney {

    public static int first_denomination(int kinds_of_coin) {
    switch (kinds_of_coin) {
    case 1: {
    return 1;
    }
    case 2: {
    return 5;

    }
    case 3: {
    return 10;

    }
    case 4: {
    return 25;

    }
    case 5: {
    return 50;

    }
    default:
    return 0;
    }

    }

    public static int cc(int amount, int kinds_of_coin) {
    if (amount==0) {
    return 1;
    } else if (amount<0||kinds_of_coin==0) {
    return 0;
    } else {
    return cc(amount, kinds_of_coin-1) + cc(amount - first_denomination(kinds_of_coin), kinds_of_coin);
    }
    }

    public static int count_change(int amount) {
    return cc(amount, 5);
    }

    public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    System.out.println(count_change(1000));
    long endTime = System.currentTimeMillis();
    System.out.println("程序运行时间:"+(endTime-startTime)+"ms");
    }
    }
  • 相关阅读:
    如何创建并运行Java线程
    PHP捕获Fatal error错误与异常处理
    WEB系统启动时加载Log4j的配置文件
    Log4j日志配置
    CharacterEncodingFilter-Spring字符编码过滤器
    Struts2的属性驱动与模型驱动的区别
    Filter之——GZIP全站压缩
    乱码问题总结
    【总结】编写自己的JDBC框架
    四大域总结
  • 原文地址:https://www.cnblogs.com/R4mble/p/7881868.html
Copyright © 2020-2023  润新知