【问题标题】:How to get exchange by coins with two denominations?两种面额的硬币如何兑换?
【发布时间】:2020-05-29 15:07:08
【问题描述】:

开发一个方法change(amount),对于 24 到 1000 范围内的任何整数数量,返回一个仅由数字 5 和 7 组成的列表,使得它们的总和等于数量。例如,change(28) 可能返回[7, 7, 7, 7],而change(49) 可能返回[7, 7, 7, 7, 7, 7, 7][5, 5, 5, 5, 5, 5, 5, 7, 7][7, 5, 5, 5, 5, 5, 5, 5, 7]

我写过这样的东西。但它不能正常工作。

enter code here

def change (amount):
assert (amount >=24)
if amount == 24:
    return [5, 5, 7, 7]
if amount == 29:
    return [5, 5, 5, 7, 7]
if amount == 40:
    return [5, 5, 5, 5, 5, 5, 5, 5]


coins = change(amount - 5)
coins.append(5)
return coins

对于范围内的硬币(24, 1000): 打印(硬币)

【问题讨论】:

标签: logic


【解决方案1】:

其实你应该找到两个数字:

  • 值为 7 的硬币数量(设为 countA)和
  • 值为 5 的硬币数量(设为 countB

如您所见0 <= countA <= sum/7。那么sum - countA * 7 应该被 5 除以没有余数

那么,java中的简单实现可以是这样的:

import java.util.Collections;
// ... 
public List<Integer> getExchange(int sum)
{
   int coinA = 7;
   int coinB = 5;

   int maxCountOfCoinA = sum / coinA;
   int countA = 0;
   int countB = 0;
   for (int count = 0; count <= maxCountOfCoinA; count++)
   {
      int remains = sum - count * coinA;
      if (remains % coinB == 0)
      {
         countA = count;
         countB = remains / coinB;
         break;
      }
   }

   List<Integer> result = new ArrayList<>();
   result.addAll(Collections.nCopies(countA, coinA));
   result.addAll(Collections.nCopies(countB, coinB));
   return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多