编程练习-找零钱

老村长在村口支了一个西瓜摊卖西瓜,规定每人只能买一个瓜,一个瓜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;
}
原文地址:https://www.cnblogs.com/zhengze/p/15089448.html