查詢我們銷售總金額的 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;
}輸入
{10, 15, 10, 5}, "14214331"輸出
75
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP