Find the largest number smaller than integer N with maximum number of set bits - GeeksforGeeks

17 Nov, 2021
Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: 
Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary representation is 10 with 1 set bit, and 1 has maximum number of set bits less than the integer N.  
 
Naive Approach:The naive way to solve the above problem is to iterate till the integer N and find the number of set bits of each number and store the number having the largest set bits at each step.Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){    int num = 0;     int max_setBits = 0;     // Iterate through all the numbers    for (int i = 0; i <= n; i++) {         // Find the number of set bits        // for the current number        int setBits = __builtin_popcount(i);         // Check if this number has the        // highest set bits        if (setBits >= max_setBits) {            num = i;            max_setBits = setBits;        }    }     // Return the result    return num;} // Driver codeint main(){    int N = 345;     cout << largestNum(N);     return 0;}
// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsclass GFG{             /* Function to get no of set    bits in binary representation    of positive integer n */    static int countSetBits(int n)    {        int count = 0;        while (n > 0)        {            count += n & 1;            n >>= 1;        }        return count;    }         // Function to return the largest    // number less than N    static int largestNum(int n)    {        int num = 0;             int max_setBits = 0;             // Iterate through all the numbers        for (int i = 0; i <= n; i++)        {                 // Find the number of set bits            // for the current number            int setBits = countSetBits(i);                 // Check if this number has the            // highest set bits            if (setBits >= max_setBits)            {                num = i;                max_setBits = setBits;            }        }             // Return the result        return num;    }         // Driver code    public static void main (String[] args)    {        int N = 345;             System.out.println(largestNum(N));    }} // This code is contributed by AnkitRai01
# Python3 implementation to find the# largest number smaller than integer# N with maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n):     num = 0;    max_setBits = 0;     # Iterate through all the numbers    for i in range(n + 1):         # Find the number of set bits        # for the current number        setBits = bin(i).count('1');         # Check if this number has the        # highest set bits        if (setBits >= max_setBits):            num = i;            max_setBits = setBits;     # Return the result    return num; # Driver codeif __name__ == "__main__" :     N = 345;     print(largestNum(N)); # This code is contributed by AnkitRai01
// C# implementation to Find the// largest number smaller than integer// N with a maximum number of set bitsusing System;     class GFG{        // Function to get no of set// bits in binary representation// of positive integer nstatic int countSetBits(int n){    int count = 0;    while (n > 0)    {        count += n & 1;        n >>= 1;    }    return count;}     // Function to return the largest// number less than Nstatic int largestNum(int n){    int num = 0;    int max_setBits = 0;         // Iterate through all the numbers    for(int i = 0; i <= n; i++)    {               // Find the number of set bits       // for the current number       int setBits = countSetBits(i);               // Check if this number has       // the  highest set bits       if (setBits >= max_setBits)       {           num = i;           max_setBits = setBits;       }    }         // Return the result    return num;}     // Driver codepublic static void Main(String[] args){    int N = 345;         Console.Write(largestNum(N));}} // This code is contributed by shivanisinghss2110
<script>     // Javascript implementation to Find the    // largest number smaller than integer    // N with a maximum number of set bits         // Function to get no of set    // bits in binary representation    // of positive integer n    function countSetBits(n)    {        let count = 0;        while (n > 0)        {            count += n & 1;            n >>= 1;        }        return count;    }     // Function to return the largest    // number less than N    function largestNum(n)    {        let num = 0;        let max_setBits = 0;         // Iterate through all the numbers        for(let i = 0; i <= n; i++)        {            // Find the number of set bits           // for the current number           let setBits = countSetBits(i);            // Check if this number has           // the  highest set bits           if (setBits >= max_setBits)           {               num = i;               max_setBits = setBits;           }        }         // Return the result        return num;    }         let N = 345;           document.write(largestNum(N)); </script>
255
 
Time Complexity: O(n)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above solution we have to observe that the number with the highest set bits will surely be of form 2k – 1. So we only need to iterate over the possible values of k and find the highest value just less than the integer N. Since we are iterating over the exponent variable therefore at most log(N) steps will be required.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){     int num = 0;     // Iterate through all possible values    for (int i = 0; i <= 32; i++)    {        // Multiply the number by 2 i times        int x = (1 << i);         if ((x - 1) <= n)            num = (1 << i) - 1;         else            break;    }     // Return the final result    return num;} // Driver codeint main(){    int N = 345;     cout << largestNum(N);     return 0;}
// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsimport java.util.*;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){    int num = 0;     // Iterate through all possible values    for (int i = 0; i <= 32; i++)    {        // Multiply the number by 2 i times        int x = (1 << i);         if ((x - 1) <= n)            num = (1 << i) - 1;         else            break;    }     // Return the final result    return num;} // Driver codepublic static void main(String args[]){    int N = 345;     System.out.print(largestNum(N));}} // This code is contributed by Akanksha_Rai
# Python3 implementation to find the# largest number smaller than integer# N with the maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n):     num = 0;     # Iterate through all possible    # values    for i in range(32):         # Multiply the number by        # 2 i times        x = (1 << i);         if ((x - 1) <= n):            num = (1 << i) - 1;        else:            break;     # Return the final result    return num; # Driver codeif __name__ == "__main__":     N = 345;     print(largestNum(N)); # This code is contributed by AnkitRai01
// C# implementation to Find the// largest number smaller than integer// N with maximum number of set bitsusing System;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){    int num = 0;     // Iterate through all possible values    for (int i = 0; i <= 32; i++)    {        // Multiply the number by 2 i times        int x = (1 << i);         if ((x - 1) <= n)            num = (1 << i) - 1;         else            break;    }     // Return the final result    return num;} // Driver codepublic static void Main(){    int N = 345;     Console.Write(largestNum(N));}} // This code is contributed by Nidhi_Biet
<script>    // Javascript implementation to Find the    // largest number smaller than integer    // N with maximum number of set bits         // Function to return the largest    // number less than N    function largestNum(n)    {         let num = 0;         // Iterate through all possible values        for (let i = 0; i <= 32; i++)        {            // Multiply the number by 2 i times            let x = (1 << i);             if ((x - 1) <= n)                num = (1 << i) - 1;             else                break;        }         // Return the final result        return num;    }     let N = 345;      document.write(largestNum(N));         // This code is contributed by suresh07.</script>
255
 
Time Complexity: O(log N)
Auxiliary Space: O(1) 
ankthon
nidhi_biet
Akanksha_Rai
shivanisinghss2110
divyesh072019
suresh07
souravmahato348
Bit Magic
Greedy
Mathematical
Greedy
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Program to find parity
Bit Fields in C
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Program for array rotation