ในปัญหานี้ เราได้รับอาร์เรย์ arr[] ซึ่งประกอบด้วยค่าอักขระ n ค่าที่แสดงนิพจน์ งานของเราคือ ประเมินนิพจน์อาร์เรย์ด้วยตัวเลข + และ –
นิพจน์ประกอบด้วยเท่านั้น ตัวเลข อักขระ '+' และอักขระ '- '
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
ป้อนข้อมูล: 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