TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
power_of_two.cpp
Go to the documentation of this file.
1
24
25
#include <iostream>
26
#include <cassert>
27
28
33
namespace
math
{
42
int
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
59
static
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
79
void
user_input_test
() {
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
99
int
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
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math
for assert
math::power_of_two
int power_of_two(int n)
This function finds whether a number is power of 2 or not.
Definition
power_of_two.cpp:42
user_input_test
void user_input_test()
Take user input in the test cases (optional; currently commented).
Definition
power_of_two.cpp:79
math
power_of_two.cpp
Generated by
1.18.0