TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
power_of_two.cpp
Go to the documentation of this file.
1
25#include <iostream>
26#include <cassert>
27
28
33namespace math {
42int power_of_two(int n) {
45 int result = n & (n - 1);
46
47 if (result == 0) {
48 return 1;
49 }
50
51 return 0;
52}
53} // namespace math
54
59static void test() {
60 std::cout << "First case testing... \n"; // for n = 32 return 1
61 assert(math::power_of_two(32) == 1);
62 std::cout << "\nPassed!\n";
63
64 std::cout << "Second case testing... \n"; // for n = 5 return 0
65 assert(math::power_of_two(5) == 0);
66 std::cout << "\nPassed!\n";
67
68 std::cout << "Third case testing... \n"; // for n = 232 return 0
69 assert(math::power_of_two(232) == 0);
70 std::cout << "\nPassed!\n";
71
72 std::cout << "\nAll test cases have successfully passed!\n";
73}
74
80 int n = 0; // input from user
81
82 std::cout << "Enter a number " << std::endl;
83 std::cin >> n;
84
86 int result = math::power_of_two(n);
87 if (result == 1) {
88 std::cout << "Yes, the number " << n << " is a power of 2\n";
89 }
90 else {
91 std::cout << "No, the number " << n << " is not a power of 2\n";
92 }
93}
94
99int main() {
100 test(); // run self-test implementations
101
102 // uncomment the line below to take user inputs
103 //user_input_test();
104
105 return 0;
106}
for assert
int 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.