TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
power_of_2.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <cstdint>
20#include <iostream>
21
26namespace bit_manipulation {
32bool isPowerOfTwo(std ::int64_t n) { // int64_t is preferred over int so that
33 // no Overflow can be there.
34
35 return n > 0 && !(n & n - 1); // If we subtract a power of 2 numbers by 1
36 // then all unset bits after the only set bit become set; and the set bit
37 // becomes unset.
38
39 // If a number n is a power of 2 then bitwise and of n-1 and n will be zero.
40 // The expression n&(n-1) will not work when n is 0.
41 // To handle this case also, our expression will become n& (!n&(n-1))
42}
43} // namespace bit_manipulation
44
49static void test() {
50 // n = 4 return true
51 assert(bit_manipulation::isPowerOfTwo(4) == true);
52 // n = 6 return false
53 assert(bit_manipulation::isPowerOfTwo(6) == false);
54 // n = 13 return false
55 assert(bit_manipulation::isPowerOfTwo(13) == false);
56 // n = 64 return true
57 assert(bit_manipulation::isPowerOfTwo(64) == true);
58 // n = 15 return false
59 assert(bit_manipulation::isPowerOfTwo(15) == false);
60 // n = 32 return true
61 assert(bit_manipulation::isPowerOfTwo(32) == true);
62 // n = 97 return false
63 assert(bit_manipulation::isPowerOfTwo(97) == false);
64 // n = 1024 return true
65 assert(bit_manipulation::isPowerOfTwo(1024) == true);
66 std::cout << "All test cases successfully passed!" << std::endl;
67}
72int main() {
73 test(); // run self-test implementations
74 return 0;
75}
bool isPowerOfTwo(std ::int64_t n)
The main function implements check for power of 2.
static void test()
Self-test implementations.
int main()
Main function.