w3resource logo


php exercises

PHP Challenges: Check if a given positive integer is a power of two

PHP Challenges - 1: Exercise-1 with Solution

Write a PHP program to check if a given positive integer is a power of two.

Input : 4
Output :4 is power of 2

Explanation :

PHP: Check if a given positive integer is a power of two

Sample Solution :-

PHP Code :

<?php
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(36)."\n");
print_r(is_Power_of_two(16)."\n");
?>

Output :

4 is power of 2                                             
36 is not power of 2                                        
16 is power of 2

Flowchart:

PHP Flowchart: Check if a given positive integer is a power of two

PHP Code Editor:

<?php
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(36)."\n");
print_r(is_Power_of_two(16)."\n");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables