Start learning free

LESSON 658 OF 674 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Payment Fees

Practice O(1)

A shop takes payments by card, by PayPal and in cash. Every payment has an amount, in cents, and a total: the amount plus a processing fee. The total is worked out the same way for every payment; only the fee depends on the kind of payment. That is what an abstract class is for: it holds the shared part, says that every payment has a fee, and leaves the fee itself to each kind of payment.

  • The abstract class Payment is built from an amount, in cents, and keeps it. Its method Fee() is abstract: every payment has a fee, but Payment can't say what it is. Its method Total() is concrete: it returns the amount plus Fee().
  • Card, PayPal and Cash inherit from Payment, keep its Total() as it is, and each writes its own Fee():
  • Card pays 2%: its fee is amount × 2 / 100.
  • PayPal pays 3% plus 30 cents: its fee is amount × 3 / 100 + 30.
  • Cash costs nothing: its fee is 0.

In C#, Payment is an abstract class and Fee is declared public abstract int Fee();, with no body. Each subclass inherits with : Payment, hands its amount to Payment's constructor with : base(amount), and overrides Fee. Method names start with a capital letter, and dividing two ints drops the fraction.

Every division rounds down: a card payment of 1999 cents has a fee of 39, not 39.98.

The starter code already has every class, every constructor and every method header: declare the field and the abstract method, and write the bodies. For each test, the harness creates the payments in the order given and prints two lines: each payment's total, Total(), separated by spaces, and then the sum of all the fees. It calls them through the abstract type Payment, never through Card, PayPal or Cash.

 

Example 1:

Input:
    new Card(1999)
    new PayPal(500)
    new Cash(700)
Output:
    2038 545 700
    84
Explanation: The card's fee is 1999 × 2 / 100 = 39 (39.98 rounded down), so its total is 2038. PayPal's fee is 500 × 3 / 100 + 30 = 45, total 545. Cash has no fee: total 700. The fees add up to 39 + 45 + 0 = 84.

Example 2:

Input:
    new Card(49)
    new PayPal(33)
    new Card(50)
Output:
    49 63 51
    31
Explanation: 49 × 2 / 100 is 0.98, rounded down to 0. PayPal's 33 × 3 / 100 is 0.99, rounded down to 0, plus 30. The second card's 50 × 2 / 100 is exactly 1. The fees are 0 + 30 + 1 = 31.

Example 3:

Input:
    new Card(0)
    new PayPal(0)
    new Cash(0)
Output:
    0 30 0
    30
Explanation: Amounts can be 0. PayPal still adds its 30 cents.

 

Constraints:

  • Every test has between 1 and 100 payments.
  • Every amount is an integer from 0 to 106 cents.

Note:

Every fee and every total takes O(1) time.

STEP 1 OF 7
    Ctrl + Enter to check