Sometimes it is OK to try all permutations II
This one in particular only requires 3! permutations (also known as 6), the solution however is more generic for any number, although still an N! solution. Used Claude to help me refresh how to go from BigInteger to binary and vice-versa. Cheers, ACC
Maximum Possible Number by Binary Concatenation - LeetCode
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
public class Solution { public int MaxGoodNumber(int[] nums) { BigInteger retVal = 0; MaxGoodNumber(nums, new HashSet(), "", ref retVal); return (int)retVal; } private void MaxGoodNumber(int[] nums, HashSet usedIndex, string currentNumberBinary, ref BigInteger maxNumberBinary) { if (usedIndex.Count == nums.Length) { BigInteger num = BinaryStringToBigInteger(currentNumberBinary); if (num > maxNumberBinary) maxNumberBinary = num; return; } for (int i = 0; i < nums.Length; i++) { if (!usedIndex.Contains(i)) { usedIndex.Add(i); MaxGoodNumber(nums, usedIndex, currentNumberBinary + Convert.ToString(nums[i], 2), ref maxNumberBinary); usedIndex.Remove(i); } } } public static BigInteger BinaryStringToBigInteger(string binary) { BigInteger result = 0; foreach (char c in binary) { result <<= 1; // Shift left by 1 if (c == '1') result += 1; } return result; } }
Comments
Post a Comment