Maximum Possible Number by Binary Concatenation
MediumUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
Example 1
Input: nums = [1,2,3]
Output: 30
Explanation:
Concatenate the numbers in the order `[3, 1, 2]` to get the result `"11110"`,
which is the binary representation of 30.
Example 2
Input: nums = [2,8,16]
Output: 1296
Explanation:
Concatenate the numbers in the order `[2, 8, 16]` to get the result
`"10100010000"`, which is the binary representation of 1296.
Constraints
nums.length == 31 <= nums[i] <= 127
Solution
Method 1 – Permutation and Binary Concatenation
Intuition
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.
Approach
- Generate all permutations of the input array
nums(there are only 6 for 3 elements). - For each permutation:
- Convert each number to its binary string (no leading zeros).
- Concatenate the binary strings in the order of the permutation.
- Convert the concatenated string to an integer (base 2).
- Track the maximum value found.
- Return the maximum value.
Code
C++
class Solution {
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;
}
};
Go
import "strconv"
func maximumBinaryNumber(nums []int) int {
ans := 0
perm := func(a []int, f func([]int)) {
var generate func(int)
generate = func(n int) {
if n == 1 {
tmp := make([]int, len(a))
copy(tmp, a)
f(tmp)
return
}
for i := 0; i < n; i++ {
generate(n-1)
if n%2 == 1 {
a[0], a[n-1] = a[n-1], a[0]
} else {
a[i], a[n-1] = a[n-1], a[i]
}
}
}
generate(len(a))
}
perm(nums, func(p []int) {
s := ""
for _, x := range p {
b := strconv.FormatInt(int64(x), 2)
s += b
}
v, _ := strconv.ParseInt(s, 2, 64)
if int(v) > ans {
ans = int(v)
}
})
return ans
}
Java
class Solution {
public int maximumBinaryNumber(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;
}
private boolean nextPermutation(List<Integer> nums) {
int i = nums.size() - 2;
while (i >= 0 && nums.get(i) >= nums.get(i+1)) i--;
if (i < 0) return false;
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()));
return true;
}
}
Kotlin
class Solution {
fun maximumBinaryNumber(nums: IntArray): Int {
var ans = 0
fun nextPermutation(a: IntArray): Boolean {
var i = a.size - 2
while (i >= 0 && a[i] >= a[i+1]) i--
if (i < 0) return false
var j = a.size - 1
while (a[j] <= a[i]) j--
a[i] = a[j].also { a[j] = a[i] }
a.reverse(i+1, a.size)
return true
}
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
}
private fun IntArray.reverse(from: Int, to: Int) {
var l = from
var r = to - 1
while (l < r) {
this[l] = this[r].also { this[r] = this[l] }
l++
r--
}
}
}
Python
from itertools import permutations
class Solution:
def maximumBinaryNumber(self, nums: list[int]) -> int:
ans = 0
for p in permutations(nums):
s = ''.join(bin(x)[2:] for x in p)
ans = max(ans, int(s, 2))
return ans
Rust
impl Solution {
pub fn maximum_binary_number(nums: Vec<i32>) -> i32 {
let mut ans = 0;
let mut arr = nums.clone();
arr.sort();
loop {
let s: String = arr.iter().map(|&x| format!("{:b}", x)).collect();
let v = i32::from_str_radix(&s, 2).unwrap();
ans = ans.max(v);
if !next_permutation(&mut arr) { break; }
}
ans
}
}
fn next_permutation(nums: &mut [i32]) -> bool {
let n = nums.len();
if n < 2 { return false; }
let mut i = n - 2;
while i != usize::MAX && nums[i] >= nums[i+1] { if i == 0 { break; } i -= 1; }
if nums[i] >= nums[i+1] { return false; }
let mut j = n - 1;
while nums[j] <= nums[i] { j -= 1; }
nums.swap(i, j);
nums[i+1..].reverse();
true
}
TypeScript
class Solution {
maximumBinaryNumber(nums: number[]): number {
let ans = 0;
const permute = (arr: number[], l: number) => {
if (l === arr.length) {
const s = arr.map(x => x.toString(2)).join("");
const v = parseInt(s, 2);
ans = Math.max(ans, v);
return;
}
for (let i = l; i < arr.length; ++i) {
[arr[l], arr[i]] = [arr[i], arr[l]];
permute(arr, l+1);
[arr[l], arr[i]] = [arr[i], arr[l]];
}
};
permute(nums, 0);
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(3! * 3); there are 6 permutations, and for each, we concatenate 3 binary strings. - 🧺 Space complexity:
O(1); only a few variables are used, as the input size is constant.