TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Implementation to check whether a number is a power of 2 or not. More...
#include <iostream>
#include <cassert>
Go to the source code of this file.
Namespaces | |
namespace | math |
for assert | |
Functions | |
int | math::power_of_two (int n) |
This function finds whether a number is power of 2 or not. | |
static void | test () |
Self-test implementations. | |
void | user_input_test () |
Take user input in the test cases (optional; currently commented) | |
int | main () |
Main function. | |
Implementation to check whether a number is a power of 2 or not.
This algorithm uses bit manipulation to check if a number is a power of 2 or not.
Let the input number be n, then the bitwise and between n and n-1 will let us know whether the number is power of 2 or not
For Example, If N= 32 then N-1 is 31, if we perform bitwise and of these two numbers then the result will be zero, which indicates that it is the power of 2 If N=23 then N-1 is 22, if we perform bitwise and of these two numbers then the result will not be zero , which indicates that it is not the power of 2
Definition in file power_of_two.cpp.
int main | ( | void | ) |
Main function.
Definition at line 99 of file power_of_two.cpp.
|
static |
Self-test implementations.
Definition at line 59 of file power_of_two.cpp.
void user_input_test | ( | ) |
Take user input in the test cases (optional; currently commented)
function call with
n |
Definition at line 79 of file power_of_two.cpp.