查找我们销售总金额的 C++ 代码
假设我们正在销售 4 件商品,第 i 件商品的价格在数组 'cost[i]' 中给出。现在我们按照字符串 'items' 中给出的顺序销售商品。我们必须找出我们已经销售的总金额。字符串 'items' 包含 1 到 4 之间的整数,可能存在重复项,并且它们可以按任何顺序排列。
所以,如果输入为 cost = {10, 15, 10, 5},items = "14214331",那么输出将为 75。
步骤
要解决此问题,我们将遵循以下步骤 −
total := 0 for initialize i := 0, when i < size of items, update (increase i by 1), do: total := total + cost[items[i] - '0' - 1] return total
示例
让我们看看以下实现以获得更好的理解
#include <bits/stdc++.h> using namespace std; #define N 100 int solve(int cost[], string items) { int total = 0; for(int i = 0; i < items.size(); i++) total += cost[items[i] -'0' - 1]; return total; } int main() { int cost[] = {10, 15, 10, 5}; string items = "14214331"; cout<< solve(cost, items); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
{10, 15, 10, 5}, "14214331"
输出
75
广告