Last active
August 10, 2021 13:20
-
-
Save tounsils/d13d9efea1964c4f5b0f4c3ca81cf187 to your computer and use it in GitHub Desktop.
Write a PHP program to check if a given positive integer is a power of two.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Write a PHP program to check if a given positive integer is a power of two. | |
* Input : 4 | |
* | |
* | |
* Example (positive): | |
* n = 32 | |
* than in binary representation | |
* n = 100000 | |
* Then n - 1 = 011111 So if you take n - 1 & n you get 0. | |
* Example (negative): | |
* n = 6 | |
* than in binary representation | |
* n = 110 | |
* Now | |
* n - 1 = 101 | |
* So ((n - 1) & n) == 100 > 0. | |
*/ | |
function is_Power_of_two($n) | |
{ | |
if(($n & ($n - 1)) == 0) | |
{ | |
return "$n is power of 2"; | |
} | |
else | |
{ | |
return "$n is not power of 2"; | |
} | |
} | |
print_r(is_Power_of_two(4)."\n"); | |
print_r(is_Power_of_two(37)."\n"); | |
print_r(is_Power_of_two(16)."\n"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment