Sum the invoice line items
An invoice lists items with quantity and unit price. Compute the total across all lines.
- Each line contributes qty multiplied by unitPrice.
- An empty list totals zero.
invoiceLineTotal(items: list<LineItem>) → 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 invoiceLineTotal(items []LineItem) int {
}
Worked examples
| Call | Result |
|---|---|
invoiceLineTotal([]LineItem{LineItem{Name: "Widget", Qty: 3, UnitPrice: 500}}) | 1500 |
invoiceLineTotal([]LineItem{LineItem{Name: "A", Qty: 2, UnitPrice: 1000}, LineItem{Name: "B", Qty: 1, UnitPrice: 300}}) | 2300 |
invoiceLineTotal([]LineItem{}) | 0 |
invoiceLineTotal([]LineItem{LineItem{Name: "X", Qty: 0, UnitPrice: 999}}) | 0 |
Hint
Walk the list, multiply each line, and add.
Reference solution in Go
func invoiceLineTotal(items []LineItem) int {
total := 0
for _, item := range items {
total += item.Qty * item.UnitPrice
}
return total
}