使用 C++ 計算包含數字、+ 和 - 的陣列表示式
本題中,我們給定了一個包含 n 個字元值表示表示式的陣列 arr[]。我們的任務是計算包含數字、+ 和 - 的陣列表示式。
表示式僅包含數字、‘+’字元和‘-’字元。
舉個例子來理解這個問題,
輸入:arr = {“5”, “+”, “2”, “-8”, “+”, “9”,}
輸出: 8
解釋:
表示式為 5 + 2 - 8 + 9 = 8
解決方案方法
該問題的解決方案是執行每個操作,然後返回該值。每個數字都需要轉換成它等效的整數。
一個程式來說明解決方案的工作原理:,
示例
#include <bits/stdc++.h>
using namespace std;
int solveExp(string arr[], int n) {
if (n == 0)
return 0;
int value, result;
result = stoi(arr[0]);
for (int i = 2; i < n; i += 2)
{
int value = stoi(arr[i]);
if (arr[i - 1 ] == "+")
result += value;
else
result -= value;
}
return result;
}
int main() {
string arr[] = { "5", "-", "3", "+", "8", "-", "1" };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The solution of the equation is "<<solveExp(arr, n);
return 0;
}輸出 -
The solution of the equation is 9
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP