zoukankan      html  css  js  c++  java
  • 编程练习-找零钱

    老村长在村口支了一个西瓜摊卖西瓜,规定每人只能买一个瓜,一个瓜5元。

    村民们手里有5元,10元,20元币值的钱。

    拿5元买瓜,不用找零。

    拿10元买瓜,需要找零5元。

    拿20元买瓜,需要找零15元。

    请写出一个函数,检查老村长能否对排队买瓜的所有人找零钱,如果能,返回true,否则,返回false。

    结题思路:

    收到5元,不用找零。

    收到10元,就要看有没有5元找零。

    收到20元,找零15元。就要看有没有一张10元,一张5元或三张5元。

    所以需要知道每次找零时5元和10元的剩余数量。

    go实现:

    package main

    import
    "fmt" func coinChange(coin_list []int) bool { var five, ten = 0, 0 fmt.Println(coin_list) for _, v := range coin_list { if v == 5 { five++ } if v == 10 { if five > 0 { five-- ten++ } else { return false } } if v == 20 { if five > 0 && ten > 0 { five-- ten-- } else if five >= 3 {
              five = five - 3
           }
    else { return false } } } return true } func main() { var coin_list = []int{5, 10, 5, 20} fmt.Println(coinChange(coin_list)) }

     python实现:

    def coinChange(coin_list):
        five = ten = 0
        for coin in coin_list:
            if coin == 5:
                five += 1
            if coin == 10:
                if five:
                    five -= 1
                    ten += 1
                else:
                    return False
            if coin == 20:
                if five and ten:
                    five -= 1
                    ten += 1
                elif five >= 3:
                    five -= 3
                else:
                    return False
        return True
    
    if __name__ == '__main__':
        coin_list = [5, 5, 10 ,10, 20]
        print(coinChange(coin_list))

     c++实现:

    #include<iostream>
    #include<vector>
    
    using namespace std;
    
    
    bool coinChange(vector<int>& bills) {
        int five, ten = 0;
        for(auto& bill: bills) {
            if(bill == 5) {
                five++;
            }
            if(bill == 10) {
                if(five > 0) {
                    five++;
                    ten--;
                } else {
                    return false;
                }
            }
            if(bill == 20) {
                if (five > 0 && ten > 0) {
                    five--;
                    ten--;
                } else if (five >= 3) {
                    five = five - 3;
                } else {
                    return false;
                }
            }
        } 
    
        return true;
    }
    
    
    int main(){
        int coinList[] = {5, 5, 10, 20};
        vector<int> bills(coinList, coinList+4);
        bool res = coinChange(bills);
        cout << "res:" << bool(res) << endl;
        return 0;
    }
  • 相关阅读:
    gulp模块编译
    微擎数据库表-T
    微信小程序自动识别姓名电话地址
    PHPBase64格式编码图片
    HTML中Data的数据类型
    EPP状态码
    WePay-T
    HTML-T
    PHPNamespace命名空间
    jQuery:jQuery简介
  • 原文地址:https://www.cnblogs.com/zhengze/p/15089448.html
Copyright © 2011-2022 走看看