Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
bit_manipulation Namespace Reference

for IO operations More...

Functions

bool isPowerOfTwo (std ::int64_t n)
 The main function implements check for power of 2.
 

Detailed Description

for IO operations

Bit manipulation algorithms.

for io operations

storing the numbers

for assert

Bit manipulation algorithms

for assert for IO operations

Bit manipulation algorithms

for assert

Bit Manipulation algorithms

for std::min for assert for IO operations for limits of integral types for std::vector

Function Documentation

◆ isPowerOfTwo()

bool bit_manipulation::isPowerOfTwo ( std ::int64_t  n)

The main function implements check for power of 2.

Parameters
nis the number who will be checked
Returns
either true or false
31 { // int64_t is preferred over int so that
32 // no Overflow can be there.
33
34 return n > 0 && !(n & n - 1); // If we subtract a power of 2 numbers by 1
35 // then all unset bits after the only set bit become set; and the set bit
36 // becomes unset.
37
38 // If a number n is a power of 2 then bitwise and of n-1 and n will be zero.
39 // The expression n&(n-1) will not work when n is 0.
40 // To handle this case also, our expression will become n& (!n&(n-1))
41}