Work out the shipping charge
The carrier bills in weight bands, and anything over five kilos is charged per extra kilo started.
- Up to 500 g costs 3000. Up to 2 kg, 5000. Up to 5 kg, 8000.
- Above 5 kg it is 8000 plus 1500 for every extra kilo begun — 5100 g pays for one extra kilo, 6001 g pays for two.
- Express doubles whatever the total came to.
- Zero or negative weight costs nothing, express or not.
shippingCost(grams: int, express: bool) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func shippingCost(grams int, express bool) int {
}
Worked examples
| Call | Result |
|---|---|
shippingCost(400, false) | 3000 |
shippingCost(500, false) | 3000 |
shippingCost(1500, false) | 5000 |
shippingCost(5000, false) | 8000 |
Hint
For the top band, round the excess up to whole kilos: (excess + 999) / 1000 in integer arithmetic.
Reference solution in Go
func shippingCost(grams int, express bool) int {
if grams <= 0 {
return 0
}
var cost int
switch {
case grams <= 500:
cost = 3000
case grams <= 2000:
cost = 5000
case grams <= 5000:
cost = 8000
default:
cost = 8000 + ((grams-5000+999)/1000)*1500
}
if express {
return cost * 2
}
return cost
}