Open In App

Smallest number greater or equals to N such that it has no odd positioned bit set

Given an integer N, the task is to find the smallest integer X such that it has no odd position set and X ? N
Note: The positioning of bits is assumed from the right side and the first bit is assumed to be the 0th bit. 

Examples:  



Input: N = 9 
Output: 16 
16’s binary representation is 10000, which has its 4th bit 
set which is the smallest number possible satisfying the given condition. 
Input: N = 5 
Output: 5
Input: N = 19 
Output: 20 

Approach: The problem can be solved using a greedy approach and some bit properties. The property that if smaller powers of two are taken exactly once and added up they can never exceed a higher power of two (e.g., (1 + 2 + 4) < 8). The following greedy approach is used to solve the above problem: 
 



Below is the implementation of the above approach: 
 




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the total bits
int countBits(int n)
{
    int count = 0;
 
    // Iterate and find the
    // number of set bits
    while (n) {
        count++;
 
        // Right shift the number by 1
        n >>= 1;
    }
    return count;
}
 
// Function to find the nearest number
int findNearestNumber(int n)
{
 
    // Count the total number of bits
    int cnt = countBits(n);
 
    // To get the position
    cnt -= 1;
 
    // If the last set bit is
    // at odd position then
    // answer will always be a number
    // with the left bit set
    if (cnt % 2) {
        return 1 << (cnt + 1);
    }
 
    else {
 
        int tempnum = 0;
 
        // Set all the even bits which
        // are possible
        for (int i = 0; i <= cnt; i += 2)
            tempnum += 1 << i;
 
        // If the number still is less than N
        if (tempnum < n) {
 
            // Return the number by setting the
            // next even set bit
            return (1 << (cnt + 2));
        }
 
        else if (tempnum == n)
            return n;
 
        // If we have reached this position
        // it means tempsum > n
        // hence turn off even bits to get the
        // first possible number
        for (int i = 0; i <= cnt; i += 2) {
 
            // Turn off the bit
            tempnum -= (1 << i);
 
            // If it gets lower than N
            // then set it and return that number
            if (tempnum < n)
                return tempnum += (1 << i);
        }
    }
}
 
// Driver code
int main()
{
    int n = 19;
    cout << findNearestNumber(n);
}




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function to count the total bits
    static int countBits(int n)
    {
        int count = 0;
 
        // Iterate and find the
        // number of set bits
        while (n > 0)
        {
            count++;
 
            // Right shift the number by 1
            n >>= 1;
        }
        return count;
    }
 
    // Function to find the nearest number
    static int findNearestNumber(int n)
    {
 
        // Count the total number of bits
        int cnt = countBits(n);
 
        // To get the position
        cnt -= 1;
 
        // If the last set bit is
        // at odd position then
        // answer will always be a number
        // with the left bit set
        if (cnt % 2 == 1)
        {
            return 1 << (cnt + 1);
        }
        else
        {
 
            int tempnum = 0;
 
            // Set all the even bits which
            // are possible
            for (int i = 0; i <= cnt; i += 2)
            {
                tempnum += 1 << i;
            }
 
            // If the number still is less than N
            if (tempnum < n)
            {
 
                // Return the number by setting the
                // next even set bit
                return (1 << (cnt + 2));
            }
            else
            if (tempnum == n)
            {
                return n;
            }
 
            // If we have reached this position
            // it means tempsum > n
            // hence turn off even bits to get the
            // first possible number
            for (int i = 0; i <= cnt; i += 2)
            {
 
                // Turn off the bit
                tempnum -= (1 << i);
 
                // If it gets lower than N
                // then set it and return that number
                if (tempnum < n)
                {
                    return tempnum += (1 << i);
                }
            }
        }
        return Integer.MIN_VALUE;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 19;
 
        System.out.println(findNearestNumber(n));
    }
}
 
// This code is contributed by 29AjayKumar




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to count the total bits
    static int countBits(int n)
    {
        int count = 0;
 
        // Iterate and find the
        // number of set bits
        while (n > 0)
        {
            count++;
 
            // Right shift the number by 1
            n >>= 1;
        }
        return count;
    }
 
    // Function to find the nearest number
    static int findNearestNumber(int n)
    {
 
        // Count the total number of bits
        int cnt = countBits(n);
 
        // To get the position
        cnt -= 1;
 
        // If the last set bit is
        // at odd position then
        // answer will always be a number
        // with the left bit set
        if (cnt % 2 == 1)
        {
            return 1 << (cnt + 1);
        }
        else
        {
 
            int tempnum = 0;
 
            // Set all the even bits which
            // are possible
            for (int i = 0; i <= cnt; i += 2)
            {
                tempnum += 1 << i;
            }
 
            // If the number still is less than N
            if (tempnum < n)
            {
 
                // Return the number by setting the
                // next even set bit
                return (1 << (cnt + 2));
            }
            else
            if (tempnum == n)
            {
                return n;
            }
 
            // If we have reached this position
            // it means tempsum > n
            // hence turn off even bits to get the
            // first possible number
            for (int i = 0; i <= cnt; i += 2)
            {
 
                // Turn off the bit
                tempnum -= (1 << i);
 
                // If it gets lower than N
                // then set it and return that number
                if (tempnum < n)
                {
                    return tempnum += (1 << i);
                }
            }
        }
        return int.MinValue;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 19;
 
        Console.WriteLine(findNearestNumber(n));
    }
}
 
// This code is contributed by anuj_67..




# Python implementation of the above approach
 
  
# Function to count the total bits
def countBits(n):
    count = 0;
  
    # Iterate and find the
    # number of set bits
    while (n>0):
        count+=1;
  
        # Right shift the number by 1
        n >>= 1;
    return count;
  
# Function to find the nearest number
def findNearestNumber(n):
  
    # Count the total number of bits
    cnt = countBits(n);
  
    # To get the position
    cnt -= 1;
  
    # If the last set bit is
    # at odd position then
    # answer will always be a number
    # with the left bit set
    if (cnt % 2):
        return 1 << (cnt + 1);
  
    else:
  
        tempnum = 0;
  
        # Set all the even bits which
        # are possible
        for i in range(0,cnt+1,2):
            tempnum += 1 << i;
  
        # If the number still is less than N
        if (tempnum < n):
  
            # Return the number by setting the
            # next even set bit
            return (1 << (cnt + 2));
  
        elif (tempnum == n):
            return n;
  
        # If we have reached this position
        # it means tempsum > n
        # hence turn off even bits to get the
        # first possible number
        for i in range(0,cnt+1,2):
  
            # Turn off the bit
            tempnum -= (1 << i);
  
            # If it gets lower than N
            # then set it and return that number
            if (tempnum < n):
                tempnum += (1 << i);
                return tempnum;
# Driver code
n = 19;
print(findNearestNumber(n));
 
# This code contributed by PrinciRaj1992




<script>
// Javascript implementation of the above approach
 
// Function to count the total bits
function countBits(n)
{
    let count = 0;
 
    // Iterate and find the
    // number of set bits
    while (n) {
        count++;
 
        // Right shift the number by 1
        n >>= 1;
    }
    return count;
}
 
// Function to find the nearest number
function findNearestNumber(n)
{
 
    // Count the total number of bits
    let cnt = countBits(n);
 
    // To get the position
    cnt -= 1;
 
    // If the last set bit is
    // at odd position then
    // answer will always be a number
    // with the left bit set
    if (cnt % 2) {
        return 1 << (cnt + 1);
    }
 
    else {
 
        let tempnum = 0;
 
        // Set all the even bits which
        // are possible
        for (let i = 0; i <= cnt; i += 2)
            tempnum += 1 << i;
 
        // If the number still is less than N
        if (tempnum < n) {
 
            // Return the number by setting the
            // next even set bit
            return (1 << (cnt + 2));
        }
 
        else if (tempnum == n)
            return n;
 
        // If we have reached this position
        // it means tempsum > n
        // hence turn off even bits to get the
        // first possible number
        for (let i = 0; i <= cnt; i += 2) {
 
            // Turn off the bit
            tempnum -= (1 << i);
 
            // If it gets lower than N
            // then set it and return that number
            if (tempnum < n)
                return tempnum += (1 << i);
        }
    }
}
 
// Driver code
    let n = 19;
    document.write(findNearestNumber(n));
 
</script>

Output
20

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

Another Approach: Another approach to solving this problem is to check each number starting from N until we find a number that satisfies the given conditions. Bitwise operators can be used to check if the number has odd-positioned bits set or not.

Below is the implementation of the above approach:




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the nearest number
int findNearestNumber(int n)
{
    while (true) {
        bool hasOddBitSet = false;
        int temp = n;
 
        // Check if the number has odd positioned bits set
        while (temp) {
            if (temp & 0x2)
                hasOddBitSet = true;
            temp >>= 2;
        }
 
        // If the number has no odd positioned bits set, return it
        if (!hasOddBitSet)
            return n;
 
        // Otherwise, increment the number and try again
        n++;
    }
}
 
// Driver code
int main()
{
    int n = 19;
    cout << findNearestNumber(n);
}




using System;
 
public class Program
{
    public static int FindNearestNumber(int n)
    {
        while (true)
        {
            bool hasOddBitSet = false;
            int temp = n;
 
            // Check if the number has odd positioned bits set
            while (temp > 0)
            {
                if ((temp & 0x2) != 0)
                {
                    hasOddBitSet = true;
                }
                temp >>= 2;
            }
 
            // If the number has no odd positioned bits set, return it
            if (!hasOddBitSet)
            {
                return n;
            }
 
            // Otherwise, increment the number and try again
            n++;
        }
    }
 
    public static void Main()
    {
        int n = 19;
        Console.WriteLine(FindNearestNumber(n));
    }
}




import java.util.*;
 
public class Main {
    // Function to find the nearest number
    public static int findNearestNumber(int n) {
        while (true) {
            boolean hasOddBitSet = false;
            int temp = n;
 
            // Check if the number has odd positioned bits set
            while (temp != 0) {
                if ((temp & 0x2) != 0)
                    hasOddBitSet = true;
                temp >>= 2;
            }
 
            // If the number has no odd positioned bits set, return it
            if (!hasOddBitSet)
                return n;
 
            // Otherwise, increment the number and try again
            n++;
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int n = 19;
        System.out.println(findNearestNumber(n));
    }
}




// Function to find the nearest number
function findNearestNumber(n) {
    while (true) {
        let hasOddBitSet = false;
        let temp = n;
 
        // Check if the number has odd positioned bits set
        while (temp) {
            if (temp & 0x2)
                hasOddBitSet = true;
            temp >>= 2;
        }
 
        // If the number has no odd positioned bits set, return it
        if (!hasOddBitSet)
            return n;
 
        // Otherwise, increment the number and try again
        n++;
    }
}
 
// Driver code
let n = 19;
console.log(findNearestNumber(n));




# Python3 implementation of the above approach
 
# Function to find the nearest number
def findNearestNumber(n):
 
    while True:
        hasOddBitSet = False
        temp = n
 
        # Check if the number has odd positioned bits set
        while temp != 0:
            if temp & 0x2:
                hasOddBitSet = True
            temp >>= 2
 
        # If the number has no odd positioned bits set, return it
        if not hasOddBitSet:
            return n
 
        # Otherwise, increment the number and try again
        n += 1
 
# Driver code
n = 19
print(findNearestNumber(n))

Output
20

Time Complexity: The time complexity of the given approach is O(log N) in the worst-case scenario. This is because we only need to iterate through the bits of the number once to count the total number of bits, and then perform constant time operations on the bits. The worst-case scenario would occur if we need to iterate through all the bits of the number to find the leftmost set bit.

Auxiliary Space: The auxiliary space used by the given approach is O(1) as we are not using any additional data structures, and all the operations are performed on the given number itself. Therefore, the space complexity is constant.


Article Tags :