Drill

ProblemsGo › orders

Work out the shipping charge

mediumordersMathGo

The carrier bills in weight bands, and anything over five kilos is charged per extra kilo started.

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.

Solve it in Python →

Where you start

func shippingCost(grams int, express bool) int {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More orders problems in Go