Untitled
unknown
c_cpp
5 months ago
1.9 kB
4
Indexable
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> using namespace std; // Function to convert a number from any base to base 10 long long to_base_10(const string &number, int base) { long long result = 0; for (char c : number) { result = result * base + (c - '0'); } return result; } // Function to convert a number from base 10 to any base string from_base_10(long long number, int base) { if (number == 0) return "0"; string result; bool is_negative = number < 0; if (is_negative) number = -number; while (number > 0) { result += (number % base) + '0'; number /= base; } if (is_negative) result += "-"; reverse(result.begin(), result.end()); return result; } // Function to perform arithmetic operation long long perform_operation(long long num1, long long num2, char op) { switch (op) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num2 != 0 ? num1 / num2 : 0; // Avoid division by zero default: return 0; } } int main() { int T; cin >> T; vector<string> results; while (T--) { string N1, N2, op; int B1, B2, B3; cin >> N1 >> B1 >> N2 >> B2 >> B3 >> op; // Convert numbers to base 10 long long num1 = to_base_10(N1, B1); long long num2 = to_base_10(N2, B2); // Perform the arithmetic operation long long result_in_base_10 = perform_operation(num1, num2, op[0]); // Convert the result to base B3 string result_in_base_B3 = from_base_10(result_in_base_10, B3); // Store the result results.push_back(result_in_base_B3); } // Output all results for (const string &result : results) { cout << result << endl; } return 0; }
Editor is loading...
Leave a Comment