#3309
Medium Algorithms Maximum possible number by binary concatenation
Array Bit Manipulation Enumeration
65.5% acceptance
Feb 23, 2026
115
7
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.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn max_good_number(mut nums: Vec<i32>) -> i32 {
fn bits(x: i32) -> u32 { (32 - x.leading_zeros()) as u32 }
// Sort by which concatenation order gives larger number
nums.sort_unstable_by(|&a, &b| {
let ab = (a as i64) << bits(b) | b as i64;
let ba = (b as i64) << bits(a) | a as i64;
ba.cmp(&ab)
});
let mut result = 0i32;
for x in nums {
result = (result << bits(x)) | x;
}
result
}
}