Submission
Status:
PPPPPPPPPP
Score: 100
User: admin
Problemset: วิศวกรรมข้อมูล
Language: cpp
Time: 0.002 second
Submitted On: 2024-11-25 14:39:57
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// Helper function to convert an integer to its binary string representation
string toBinary(int n) {
string binary = "";
while (n > 0) {
binary = (n % 2 == 0 ? "0" : "1") + binary;
n /= 2;
}
return binary;
}
// Custom comparator to determine which concatenation order produces the larger binary result
bool compare(int a, int b) {
string binaryA = toBinary(a);
string binaryB = toBinary(b);
return (binaryA + binaryB) > (binaryB + binaryA);
}
int maxBinaryConcatenation(vector<int>& nums) {
// Sort the numbers based on the custom comparator
sort(nums.begin(), nums.end(), compare);
// Concatenate the binary representations in the chosen order
string concatenatedBinary = "";
for (int num : nums) {
concatenatedBinary += toBinary(num);
}
// Convert the concatenated binary string back to an integer
int result = stoi(concatenatedBinary, nullptr, 2);
return result;
}
int main() {
int N;
//cout << "Enter the number of elements: ";
cin >> N;
vector<int> nums(N);
//cout << "Enter the elements: ";
for (int i = 0; i < N; ++i) {
cin >> nums[i];
}
std::cout << maxBinaryConcatenation(nums) << std::endl;
return 0;
}