3309. Maximum Possible Number by Binary Concatenation
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.
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 == 3
1 <= nums[i] <= 127
Solution:
class Solution {
public int maxGoodNumber(int[] nums) {
String one = Integer.toBinaryString(nums[0]);
String two = Integer.toBinaryString(nums[1]);
String three = Integer.toBinaryString(nums[2]);
StringBuilder sb = new StringBuilder();
sb.append(one);
sb.append(two);
sb.append(three);
StringBuilder sb1 = new StringBuilder();
sb1.append(one);
sb1.append(three);
sb1.append(two);
StringBuilder sb2 = new StringBuilder();
sb2.append(two);
sb2.append(one);
sb2.append(three);
StringBuilder sb3 = new StringBuilder();
sb3.append(two);
sb3.append(three);
sb3.append(one);
StringBuilder sb4 = new StringBuilder();
sb4.append(three);
sb4.append(one);
sb4.append(two);
StringBuilder sb5 = new StringBuilder();
sb5.append(three);
sb5.append(two);
sb5.append(one);
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a, b) -> (b - a));
int a = Integer.parseInt(sb.toString(), 2);
int b = Integer.parseInt(sb1.toString(), 2);
int c = Integer.parseInt(sb2.toString(), 2);
int d = Integer.parseInt(sb3.toString(), 2);
int e = Integer.parseInt(sb4.toString(), 2);
int f = Integer.parseInt(sb5.toString(), 2);
pq.offer(a);
pq.offer(b);
pq.offer(c);
pq.offer(d);
pq.offer(e);
pq.offer(f);
return pq.poll();
}
}
...