Feature #10: Calculate the Total Cost of the Shopping Cart Items
Implement the "Calculate the Total Cost of the Shopping Cart Items" feature for our "Amazon" project.
We'll cover the following
Description
Suppose that a customer has purchased some items online. Their shopping cart is ready for billing, and we need to calculate the total bill.
While calculating the bill, we need to consider that the customer may have purchased more than one unit of the same item. In this case, the unit price must be multiplied by the quantity. We must also consider that they may be eligible for certain discounts. Some discounts are applied as an absolute amount—for example, a $5 discount on every purchase of a 30-inch TV. Some discounts are applied as a fraction—for example, the price of a can of Coca-Cola is divided by 2
for a 50% discount.
The shopping cart is provided to us in the form of an arithmetic expression involving whole numbers and the operators +
, -
, *
, and /
. The expression is in the form of a string. We need to calculate the total cost of the items listed in the shopping cart as an integer. The rules of operator precedence in arithmetic apply here.
Let’s demonstrate this with an example.
Suppose that a customer bought an item for $2, another item for $3 with a discount of 1/7
off, and that they are eligible for $1 off their total bill because they are a loyalty club member. The string input for this calculation would be: “2 + 3 / 7 - 1”
.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.