Skip to content
Related Articles

Related Articles

Improve Article

Maximize given integer by swapping pairs of unequal bits

  • Difficulty Level : Expert
  • Last Updated : 08 Apr, 2021

Given a positive integer N, the task is to determine the maximum possible integer that can be formed by performing the following operations on the given integer N:

  • Convert the integer into its binary representation.
  • Swap only unequal bits in its binary representation.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input : 11
Output : 14
Explanation

  • (11)10 = (1011)2
  • Swap 0th bit with 2nd bit to get(1110)2 = (14)10

Input : 9
Output : 12



 

Approach: Follow the given steps to solve the problem

  • Count the number of set bits in the number N.
  • In any binary string, using the above given operations, all set bits could be moved to the left and all unset bits can be shifted towards the right. This is because any pair of unequal bits (0, 1) can be swapped, i.e. “0110110” can be converted to “1111000” using 3 operations
  • Since, by seggreagating all set bits towards the left and all unset bits towards the right maximizes the given integer.

Below is the implementation of the above approach :

C++




// C++ implementation
// of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum possible
// value that can be obtained from the
// given integer by performing given operations
int findMaxNum(int num)
{
   
    // Convert to equivalent
    // binary representation
    bitset<4> b(num);
     
    string binaryNumber = b.to_string();
 
    // Stores binary representation
    // of the maximized value
    string maxBinaryNumber = "";
 
    // Store the count of 0's and 1's
    int count0 = 0, count1 = 0;
 
    // Stores the total Number of Bits
    int N = 4;
 
    for (int i = 0; i < N; i++) {
 
        // If current bit is set
        if (binaryNumber[i] == '1') {
 
            // Increment Count1
            count1++;
        }
        else {
 
            // Increment Count0
            count0++;
        }
    }
 
    // Shift all set bits to left
    // to maximize the value
    for (int i = 0; i < count1; i++) {
        maxBinaryNumber += '1';
    }
 
    // Shift all unset bits to right
    // to maximize the value
    for (int i = 0; i < count0; i++) {
        maxBinaryNumber += '0';
    }
     
    // Return the maximized value
    return stoi(maxBinaryNumber, 0, 2);
}
 
// Driver code
int main()
{
    // Given "Input
    int N = 11;
  
    // Function call to find the
    // Maximum Possible Number
    cout << findMaxNum(N);
    return 0;
}
 
// This code is contributed by divyeshrabadiya07.

Java




// Java implementation
// of the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to return the maximum possible
    // value that can be obtained from the
    // given integer by performing given operations
    public static int findMaxNum(int num)
    {
        // Convert to equivalent
        // binary representation
        String binaryNumber
            = Integer.toBinaryString(num);
 
        // Stores binary representation
        // of the maximized value
        String maxBinaryNumber = "";
 
        // Store the count of 0's and 1's
        int count0 = 0, count1 = 0;
 
        // Stores the total Number of Bits
        int N = binaryNumber.length();
 
        for (int i = 0; i < N; i++) {
 
            // If current bit is set
            if (binaryNumber.charAt(i) == '1') {
 
                // Increment Count1
                count1++;
            }
            else {
 
                // Increment Count0
                count0++;
            }
        }
 
        // Shift all set bits to left
        // to maximize the value
        for (int i = 0; i < count1; i++) {
            maxBinaryNumber += '1';
        }
 
        // Shift all unset bits to right
        // to maximize the value
        for (int i = 0; i < count0; i++) {
            maxBinaryNumber += '0';
        }
 
        // Return the maximized value
        return Integer.parseInt(
            maxBinaryNumber, 2);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given "Input
        int N = 11;
 
        // Function call to find the
        // Maximum Possible Number
        System.out.println(findMaxNum(N));
    }
}

Python3




# Python3 implementation
# of the above approach
 
# Function to return the maximum possible
# value that can be obtained from the
# given integer by performing given operations
def findMaxNum(num):
   
    # Convert to equivalent
    # binary representation
    binaryNumber = bin(num)[2:]
 
    # Stores binary representation
    # of the maximized value
    maxBinaryNumber = ""
 
    # Store the count of 0's and 1's
    count0, count1 = 0, 0
 
    # Stores the total Number of Bits
    N = len(binaryNumber)
    for i in range(N):
 
        # If current bit is set
        if (binaryNumber[i] == '1'):
 
            # Increment Count1
            count1 += 1
        else:
 
            # Increment Count0
            count0 += 1
 
    # Shift all set bits to left
    # to maximize the value
    for i in range(count1):
        maxBinaryNumber += '1'
 
    # Shift all unset bits to right
    # to maximize the value
    for i in range(count0):
        maxBinaryNumber += '0'
 
    # Return the maximized value
    return int(maxBinaryNumber, 2)
 
# Driver Code
if __name__ == '__main__':
     
    # Given "Input
    N = 11
 
    # Function call to find the
    # Maximum Possible Number
    print(findMaxNum(N))
     
    # This code is contributed by mohit kumar 29.

C#




// C# implementation
// of the above approach
using System;
public class GFG
{
 
  // Function to return the maximum possible
  // value that can be obtained from the
  // given integer by performing given operations
  public static int findMaxNum(int num)
  {
 
    // Convert to equivalent
    // binary representation
    string binaryNumber =  Convert.ToString(num, 2);
 
    // Stores binary representation
    // of the maximized value
    string maxBinaryNumber = "";
 
    // Store the count of 0's and 1's
    int count0 = 0, count1 = 0;
 
    // Stores the total Number of Bits
    int N = binaryNumber.Length;
    for (int i = 0; i < N; i++)
    {
 
      // If current bit is set
      if (binaryNumber[i] == '1')
      {
 
        // Increment Count1
        count1++;
      }
      else
      {
 
        // Increment Count0
        count0++;
      }
    }
 
    // Shift all set bits to left
    // to maximize the value
    for (int i = 0; i < count1; i++)
    {
      maxBinaryNumber += '1';
    }
 
    // Shift all unset bits to right
    // to maximize the value
    for (int i = 0; i < count0; i++)
    {
      maxBinaryNumber += '0';
    }
 
    // Return the maximized value
    return Convert.ToInt32(maxBinaryNumber, 2);
  }
 
  // Driver Code
  static public void Main()
  {
 
    // Given "Input
    int N = 11;
 
    // Function call to find the
    // Maximum Possible Number
    Console.WriteLine(findMaxNum(N));
  }
}
 
// This code is contributed by Dharanendra L V

Javascript




<script>
 
// javascript implementation
// of the above approach
 
// Function to return the maximum possible
// value that can be obtained from the
// given integer by performing given operations
function findMaxNum(num)
{
    // Convert to equivalent
    // binary representation
    var binaryNumber
        = Number(num).toString(2);;
    // Stores binary representation
    // of the maximized value
    var maxBinaryNumber = "";
 
    // Store the count of 0's and 1's
    var count0 = 0, count1 = 0;
 
    // Stores the total Number of Bits
    var N = binaryNumber.length;
 
    for (i = 0; i < N; i++) {
 
        // If current bit is set
        if (binaryNumber.charAt(i) == '1') {
 
            // Increment Count1
            count1++;
        }
        else {
 
            // Increment Count0
            count0++;
        }
    }
 
    // Shift all set bits to left
    // to maximize the value
    for (i = 0; i < count1; i++) {
        maxBinaryNumber += '1';
    }
 
    // Shift all unset bits to right
    // to maximize the value
    for (i = 0; i < count0; i++) {
        maxBinaryNumber += '0';
    }
 
    // Return the maximized value
    return parseInt(maxBinaryNumber,2);
}
 
// Driver Code
 
 // Given "Input
var N = 11;
 
// Function call to find the
// Maximum Possible Number
document.write(findMaxNum(N));
 
// This code contributed by Princi Singh
 
</script>

 
 

Output: 
14

 

Time Complexity : O(log(N)) 
Auxiliary Space : O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :