You are given an array of integers nums of size 3.
Return the maximum possible number whose binary representation can be formed by concatenating the binary representation of all elements in
nums in some order.
Note that the binary representation of any number does not contain leading zeros.
Input: nums =[1,2,3]Output: 30Explanation:
Concatenate the numbers in the order `[3, 1, 2]` to get the result `"11110"`,which is the binary representation of 30.
Input: nums =[2,8,16]Output: 1296Explanation:
Concatenate the numbers in the order `[2, 8, 16]` to get the result
`"10100010000"`, which is the binary representation of 1296.
Since the array has only 3 elements, we can try all possible orders (permutations) to concatenate their binary representations and find the maximum value. For each permutation, we convert each number to its binary string, concatenate them, and interpret the result as a binary number.
classSolution {
public:int maximumBinaryNumber(vector<int>& nums) {
int ans =0;
sort(nums.begin(), nums.end());
do {
string s;
for (int x : nums) s += bitset<32>(x).to_string().substr(bitset<32>(x).to_string().find('1'));
ans = max(ans, (int)stoll(s, nullptr, 2));
} while (next_permutation(nums.begin(), nums.end()));
return ans;
}
};
classSolution {
publicintmaximumBinaryNumber(int[] nums) {
int ans = 0;
List<Integer> list =new ArrayList<>();
for (int x : nums) list.add(x);
Collections.sort(list);
do {
StringBuilder sb =new StringBuilder();
for (int x : list) sb.append(Integer.toBinaryString(x));
int v = Integer.parseUnsignedInt(sb.toString(), 2);
ans = Math.max(ans, v);
} while (nextPermutation(list));
return ans;
}
privatebooleannextPermutation(List<Integer> nums) {
int i = nums.size() - 2;
while (i >= 0 && nums.get(i) >= nums.get(i+1)) i--;
if (i < 0) returnfalse;
int j = nums.size() - 1;
while (nums.get(j) <= nums.get(i)) j--;
Collections.swap(nums, i, j);
Collections.reverse(nums.subList(i+1, nums.size()));
returntrue;
}
}
classSolution {
funmaximumBinaryNumber(nums: IntArray): Int {
var ans = 0funnextPermutation(a: IntArray): Boolean {
var i = a.size - 2while (i >=0&& a[i] >= a[i+1]) i--if (i < 0) returnfalsevar j = a.size - 1while (a[j] <= a[i]) j-- a[i] = a[j].also { a[j] = a[i] }
a.reverse(i+1, a.size)
returntrue }
nums.sort()
do {
val s = nums.joinToString(separator = "") { it.toString(2) }
val v = s.toInt(2)
ans = maxOf(ans, v)
} while (nextPermutation(nums))
return ans
}
privatefunIntArray.reverse(from: Int, to: Int) {
var l = from
var r = to - 1while (l < r) {
this[l] = this[r].also { this[r] = this[l] }
l++ r-- }
}
}
1
2
3
4
5
6
7
8
from itertools import permutations
classSolution:
defmaximumBinaryNumber(self, nums: list[int]) -> int:
ans =0for p in permutations(nums):
s =''.join(bin(x)[2:] for x in p)
ans = max(ans, int(s, 2))
return ans