Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIFind the largest number smaller than integer N with maximum number of...

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

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 :
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 approach to solve the problem is to iterate till the integer N – 1 and find the number of set bits for each number and store the number having the largest set bits, and max set bits of the number.
Below is the implementation of the above approach:
 

C++




// 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 N
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 = __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 code
int main()
{
    int N = 345;
 
    cout << largestNum(N);
 
    return 0;
}


Java




// Java implementation to Find the
// largest number smaller than integer
// N with maximum number of set bits
import java.io.*;
public class 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




# 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 N
def largestNum(n):
 
    num = 0;
    max_setBits = 0;
 
    # Iterate through all the numbers
    for i in range(n):
 
        # 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 code
if __name__ == "__main__" :
 
    N = 345;
 
    print(largestNum(N));
 
# This code is contributed by AnkitRai01


C#




// C# implementation to Find the
// largest number smaller than integer
// N with a maximum number of set bits
using System;
     
class 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;
     
    Console.Write(largestNum(N));
}
}
 
// This code is contributed by shivanisinghss2110


Javascript




<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>


Output

255

Time Complexity: O(n)

Auxiliary Space: O(1)

Efficient Approach: To optimize the above solution we need to observe that the number with the highest set bits will surely be of form 2k – 1. Numbers of the form 2k  will have only one bit set, and numbers of the form 2k – 1 will have all the bits set before the kth position. 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++




// 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 N
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 code
int main()
{
    int N = 345;
 
    cout << largestNum(N);
 
    return 0;
}


Java




// Java implementation to Find the
// largest number smaller than integer
// N with maximum number of set bits
import java.io.*;
class GFG{
 
// Function to return the largest
// number less than N
static 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 code
public static void main(String args[])
{
    int N = 345;
 
    System.out.print(largestNum(N));
}
}
 
// This code is contributed by Akanksha_Rai


Python3




# 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 N
def 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 code
if __name__ == "__main__":
 
    N = 345;
 
    print(largestNum(N));
 
# This code is contributed by AnkitRai01


C#




// C# implementation to Find the
// largest number smaller than integer
// N with maximum number of set bits
using System;
class GFG{
 
// Function to return the largest
// number less than N
static 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 code
public static void Main()
{
    int N = 345;
 
    Console.Write(largestNum(N));
}
}
 
// This code is contributed by Nidhi_Biet


Javascript




<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>


Output

255

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments