Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIHighest power of 2 less than or equal to given Integer

Highest power of 2 less than or equal to given Integer

Given an integer N, the task is to find the highest power of 2 that is smaller than or equal to N.

Examples: 

Input: N = 9 
Output:
Explanation: 
Highest power of 2 less than 9 is 8.

Input: N = -20 
Output: -32 
Explanation: 
Highest power of 2 less than -20 is -32.

Input: N = -84 
Output: -128 

Approach: The idea is to use logarithm to solve the above problem. For any given number N, it can be either positive or negative. The following task can be performed for each case:  

  1. If the input is positive: floor(log2(N)) can be calculated.
  2. If the input is negative: ceil(log2(N)) can be calculated and a -ve sign can be added to the value.

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 lowest power of 2 close to given
// positive number
int powOfPositive(int n)
{
    // Floor function is used to determine the value close
    // to the number
    int pos = floor(log2(n));
    return pow(2, pos);
}
 
// Function to return the lowest power of 2 close to given
// negative number
int powOfNegative(int n)
{
    // Ceil function is used for negative numbers as -1 >
    // -4. It would be opposite to positive numbers where 1 < 4
    int pos = ceil(log2(n));
    return (-1 * pow(2, pos));
}
 
// Function to find the highest power of 2
void highestPowerOf2(int n)
{
 
    // To check if the given number is positive or negative
    if (n > 0)
        cout << powOfPositive(n);
    else {
        // If the number is negative, then the ceil of the
        // positive number is calculated and negative sign
        // is added
        n = -n;
        cout << powOfNegative(n);
    }
}
 
// Driver code
int main()
{
    int n = -24;
    highestPowerOf2(n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C implementation of the above approach
#include <math.h>
#include <stdio.h>
 
// Function to return the lowest power of 2 close to given
// positive number
int powOfPositive(int n)
{
    // Floor function is used to determine the value close
    // to the number
    int pos = floor(log2(n));
    return pow(2, pos);
}
 
// Function to return the lowest power of 2 close to given
// negative number
int powOfNegative(int n)
{
    // Ceil function is used for negative numbers as -1 >
    // -4. It would be opposite to positive numbers where 1 < 4
    int pos = ceil(log2(n));
    return (-1 * pow(2, pos));
}
 
// Function to find the highest power of 2
void highestPowerOf2(int n)
{
 
    // To check if the given number is positive or negative
    if (n > 0)
        printf("%d", powOfPositive(n));
    else {
        // If the number is negative, then the ceil of the
        // positive number is calculated and negative sign
        // is added
        n = -n;
        printf("%d", powOfNegative(n));
    }
}
 
// Driver code
int main()
{
    int n = -24;
    highestPowerOf2(n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java implementation of the above approach
class GFG
{
     
    // Function to return the lowest power
    // of 2 close to given positive number
    static int powOfPositive(int n)
    {
        // Floor function is used to determine
        // the value close to the number
        int pos = (int)Math.floor((Math.log(n)/Math.log(2)));
        return (int)Math.pow(2, pos);
    }
     
    // Function to return the lowest power
    // of 2 close to given negative number
    static int powOfNegative(int n)
    {
        // Ceil function is used for negative numbers
        // as -1 > -4. It would be opposite
        // to positive numbers where 1 < 4
        int pos = (int)Math.ceil((Math.log(n)/Math.log(2)));
        return (int)(-1 * Math.pow(2, pos));
    }
     
    // Function to find the highest power of 2
    static void highestPowerOf2(int n)
    {
     
        // To check if the given number
        // is positive or negative
        if (n > 0)
        {
            System.out.println(powOfPositive(n));
        }
        else
        {
            // If the number is negative,
            // then the ceil of the positive number
            // is calculated and
            // negative sign is added
            n = -n;
            System.out.println(powOfNegative(n));
        }
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = -24;
        highestPowerOf2(n);
    }
}
 
// This code is contributed by AnkitRai01


C#




// C# implementation of the above approach
using System;
 
class GFG
{
     
    // Function to return the lowest power
    // of 2 close to given positive number
    static int powOfPositive(int n)
    {
        // Floor function is used to determine
        // the value close to the number
        int pos = (int)Math.Floor((Math.Log(n)/Math.Log(2)));
        return (int)Math.Pow(2, pos);
    }
     
    // Function to return the lowest power
    // of 2 close to given negative number
    static int powOfNegative(int n)
    {
        // Ceil function is used for negative numbers
        // as -1 > -4. It would be opposite
        // to positive numbers where 1 < 4
        int pos = (int)Math.Ceiling((Math.Log(n)/Math.Log(2)));
        return (int)(-1 * Math.Pow(2, pos));
    }
     
    // Function to find the highest power of 2
    static void highestPowerOf2(int n)
    {
     
        // To check if the given number
        // is positive or negative
        if (n > 0)
        {
            Console.WriteLine(powOfPositive(n));
        }
        else
        {
            // If the number is negative,
            // then the ceil of the positive number
            // is calculated and
            // negative sign is added
            n = -n;
            Console.WriteLine(powOfNegative(n));
        }
    }
     
    // Driver code
    public static void Main()
    {
        int n = -24;
        highestPowerOf2(n);
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the above approach
from math import floor,ceil,log2
 
# Function to return the lowest power
# of 2 close to given positive number
def powOfPositive(n) :
 
    # Floor function is used to determine
    # the value close to the number
    pos = floor(log2(n));
    return 2**pos;
 
# Function to return the lowest power
# of 2 close to given negative number
def powOfNegative(n) :
 
    # Ceil function is used for negative numbers
    # as -1 > -4. It would be opposite
    # to positive numbers where 1 < 4
    pos = ceil(log2(n));
     
    return (-1 * pow(2, pos));
 
# Function to find the highest power of 2
def highestPowerOf2(n) :
 
    # To check if the given number
    # is positive or negative
    if (n > 0) :
        print(powOfPositive(n));
 
    else :
         
        # If the number is negative,
        # then the ceil of the positive number
        # is calculated and
        # negative sign is added
        n = -n;
        print(powOfNegative(n));
 
# Driver code
if __name__ == "__main__" :
 
    n = -24;
    highestPowerOf2(n);
 
# This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript implementation of the above approach
 
// Function to return the lowest power
// of 2 close to given positive number
function powOfPositive(n)
{
     
    // Floor function is used to determine
    // the value close to the number
    let pos = Math.floor(Math.log2(n));
    return Math.pow(2, pos);
}
 
// Function to return the lowest power
// of 2 close to given negative number
function powOfNegative(n)
{
     
    // Ceil function is used for negative numbers
    // as -1 > -4. It would be opposite
    // to positive numbers where 1 < 4
    let pos = Math.ceil(Math.log2(n));
    return (-1 * Math.pow(2, pos));
}
 
// Function to find the highest power of 2
function highestPowerOf2(n)
{
 
    // To check if the given number
    // is positive or negative
    if (n > 0)
    {
        document.write(powOfPositive(n));
    }
    else
    {
         
        // If the number is negative,
        // then the ceil of the positive number
        // is calculated and
        // negative sign is added
        n = -n;
        document.write(powOfNegative(n));
    }
}
 
// Driver code
let n = -24;
 
highestPowerOf2(n);
 
// This code is contributed by mohit kumar 29
 
</script>


Output

-32

Time Complexity: O(log2(log2n))
Auxiliary Space: O(1)

Another Approach: we can use Bits manipulation in this way :

1.If number is positive- Then our answer will be pow(2,i) where i is leftmost set bit . Because if number is equal to pow(2,i), Then number is already power of 2, and  if number > pow(2,i) , any power of 2 can not be greater than pow(2,i) as in bit concepts.
2.If number is negative- Let i is leftmost set bit .Then our answer will be pow(2,i) if(pow(2,i)==num). else our answer will be pow(2,i+1) because we are taking in negative.

Below is the implementation of the above approach:  

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function find highestpowerof2 <= n
void highestPowerOf2(int n)
{ // leftmost- keep track of leftmost set bit
    int set_bits = 0, leftmost, highest;
 
    // iterate all sits of integer
    for (int i = 0; i <= 32; i++) {
        int val = pow(2, i);
 
        int Bitwise_AND = val & abs(n); // Bitwise AND
 
        if (Bitwise_AND
            > 0) // If Bitwise_AND > 0 means sit is set
        {
            leftmost = i; // update leftmost set bit
            highest = pow(
                2, leftmost); // Update
                              // highest(highestpowerof2)
            set_bits++; // count set bits
        }
        if (val >= abs(n)) {
            break;
        } // if we have found leftmost set bit ,break
    }
 
    if (n < 0) // make +highest to -highest
    {
        if (set_bits
            > 1) // means -n=-pow(2,i)-pow(2,j).....
        {
            highest = pow(2, leftmost + 1);
        }
 
        highest = -1 * highest;
    }
 
    cout << highest; // Print highestPowerOf2 <= n
}
 
// Driver code
int main()
{
    int n = -24;
 
    // Function call
    highestPowerOf2(n);
    return 0;
}
 
// This Approach is contributed by nikhilsainiofficial546


Java




import java.lang.Math;
 
class Main {
    // Function to find highest power of 2 <= n
    static void highestPowerOf2(int n) {
        int set_bits = 0, leftmost = 0, highest = 0;
         
        // iterate over all bits of integer
        for (int i = 0; i <= 31; i++) {
            int val = (int) Math.pow(2, i);
             
            int Bitwise_AND = val & Math.abs(n); // Bitwise AND
 
            if (Bitwise_AND > 0) { // If Bitwise_AND > 0 means bit is set
                leftmost = i; // update leftmost set bit
                highest = (int) Math.pow(2, leftmost); // Update highest(highest power of 2)
                set_bits++; // count set bits
            }
            if (val >= Math.abs(n)) {
                break;
            } // if we have found leftmost set bit, break
        }
         
        if (n < 0) { // make +highest to -highest
            if (set_bits > 1) { // means -n=-pow(2,i)-pow(2,j).....
                highest = (int) Math.pow(2, leftmost + 1);
            }
            highest = -1 * highest;
        }
        System.out.println(highest); // Print highest power of 2 <= n
    }
 
    // Driver code
    public static void main(String[] args) {
        int n = -24;
        highestPowerOf2(n); // Function call
    }
}


Python3




import math
 
def highestPowerOf2(n):
    set_bits = 0
    leftmost = 0
    highest = 0
     
    for i in range(32): # iterate over all bits of integer
        val = int(math.pow(2, i))
         
        Bitwise_AND = val & abs(n) # Bitwise AND
 
        if (Bitwise_AND > 0): # If Bitwise_AND > 0 means bit is set
            leftmost = i # update leftmost set bit
            highest = int(math.pow(2, leftmost)) # Update highest(highest power of 2)
            set_bits += 1 # count set bits
        if (val >= abs(n)):
            break # if we have found leftmost set bit, break
     
    if (n < 0): # make +highest to -highest
        if (set_bits > 1): # means -n=-pow(2,i)-pow(2,j).....
            highest = int(math.pow(2, leftmost + 1))
        highest = -1 * highest
     
    print(highest) # Print highest power of 2 <= n
 
# Driver code
n = -24
highestPowerOf2(n) # Function call


C#




// C# implementation of the above approach
using System;
 
class GFG {
 
  // Function find highestpowerof2 <= n
  static void highestPowerOf2(int n)
  {
 
    // leftmost- keep track of leftmost set bit
    int set_bits = 0, leftmost = 0, highest = 0;
 
    // iterate all sits of integer
    for (int i = 0; i <= 32; i++) {
      int val = (int)Math.Pow(2, i);
      int bitwiseAnd
        = val & Math.Abs(n); // Bitwise AND
 
      // If Bitwise_AND > 0 means sit is set
      if (bitwiseAnd > 0) {
        leftmost = i; // update leftmost set bit
 
        // Update highest(highestpowerof2)
        highest = (int)Math.Pow(2, leftmost);
 
        // count set bits
        set_bits++;
      }
 
      // if we have found leftmost set bit ,break
      if (val >= Math.Abs(n)) {
        break;
      }
    }
 
    // make +highest to -highest
    if (n < 0) {
      if (set_bits > 1) {
        highest = (int)Math.Pow(
          2,
          leftmost
          + 1); // means
        // -n=-pow(2,i)-pow(2,j).....
      }
 
      highest = -1 * highest;
    }
 
    Console.WriteLine(highest);
  }
 
  // Driver code
  public static void Main()
  {
    int n = -24;
 
    // Function call
    highestPowerOf2(n);
  }
}


Javascript




// JavaScript implementation of the above approach
 
// Function to find highest power of 2 <= n
function highestPowerOf2(n)
{
 
    let set_bits = 0, leftmost, highest;
 
    // Iterate all bits of the integer
    for (let i = 0; i <= 32; i++) {
        let val = Math.pow(2, i);
        let Bitwise_AND
            = val & Math.abs(n); // Bitwise AND with
                                 // absolute value of n
 
        // If Bitwise_AND > 0 means bit is set
        if (Bitwise_AND > 0) {
            leftmost = i; // Update leftmost set bit
            highest = Math.pow(
                2, leftmost); // Update highest (highest
                              // power of 2)
            set_bits++; // Count set bits
        }
 
        // If we have found leftmost set bit, break
        if (val >= Math.abs(n)) {
            break;
        }
    }
 
    // If n is negative, make +highest to -highest
    if (n < 0) {
        if (set_bits > 1) {
            // Means -n = -pow(2,i) - pow(2,j) .....
            highest = Math.pow(2, leftmost + 1);
        }
 
        highest = -1 * highest;
    }
 
    console.log(highest); // Print highest power of 2 <= n
}
 
// Driver code
let n = -24;
highestPowerOf2(n); // Output: -32


Output

-32

Time Complexity: O(log2n) , Because we are breaking loop , if leftmost set bit is found
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