Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,848 questions

51,769 answers

573 users

How to get the highest power of 2 that is less than or equal to N in C++

1 Answer

0 votes
#include <iostream>

using namespace std; 
  
int highest_power_of_2_less_or_equal_to_n(int n) { 
    int power = 0; 
    for (int i = n; i >= 1; i--) { 
        // i == power of 2 ?
        if ((i & (i - 1)) == 0) { // 10 (1010) 9 (1001) 8 (1000) 7 (0111)
            power = i; 
            break; 
        } 
    } 
    return power; 
} 
  
int main() 
{ 
    int n = 17;
    cout << highest_power_of_2_less_or_equal_to_n(n) << endl; 
    
    n = 10;
    cout << highest_power_of_2_less_or_equal_to_n(n) << endl; 
    
    n = 64;
    cout << highest_power_of_2_less_or_equal_to_n(n) << endl; 
    
    return 0; 
}



/*
run:

16
8
64

*/

 



answered Apr 13, 2019 by avibootz
edited Apr 13, 2019 by avibootz
...