自己写了个php 凑零钱方法

首页 星空物语 EXPERIENCE 正文

袅袅牧童 原创 星空物语 2023-08-09 13:16:24

简介 自己写了一个实现方法,如有错误还请指正


    public function tests()
    {

        $amount = $_GET['amount'];

        $arr = [3, 5, 2];

        $ret = [];
        $res = 0;


        $status   = true;
        $has_one  = true; //分析最小余数 1

        sort($arr);

        if (!in_array(1, $arr)) { //是否含有最小余数
            $has_one = false;
            array_unshift($arr, 1);
        }

        $count = count($arr);

        while ($status) {
            for ($i = $count - 1; $i >= 0; $i--) {

                if ($amount < $arr[$i]) continue;

                $res = $amount % $arr[$i];
                if (($res == 1 && !$has_one)) continue;

                if ($res != 0 && $res < $arr[$i-1]) continue;


                $num = floor($amount / $arr[$i]);
                $ret[] = $num . '--' . $arr[$i];

                if ($res == 0) {
                    $status = false;
                    if($arr[$i] == 1 && !$has_one){
                        $ret =false;
                    }
                    break;
                }

                $amount = $res;
            }
        }

return $ret; }

Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云