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
C++ 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
int invoiceLineTotal(std::vector<LineItem> items) {
}
Worked examples
| Call | Result |
|---|---|
invoiceLineTotal(std::vector<LineItem>{LineItem{std::string("Widget"), 3, 500}}) | 1500 |
invoiceLineTotal(std::vector<LineItem>{LineItem{std::string("A"), 2, 1000}, LineItem{std::string("B"), 1, 300}}) | 2300 |
invoiceLineTotal(std::vector<LineItem>{}) | 0 |
invoiceLineTotal(std::vector<LineItem>{LineItem{std::string("X"), 0, 999}}) | 0 |
Hint
Walk the list, multiply each line, and add.
Reference solution in C++
int invoiceLineTotal(std::vector<LineItem> items) {
int total = 0;
for (const auto& item : items) total += item.qty * item.unitPrice;
return total;
}