Pages

Thursday, May 23, 2013

C#: Find whether a number is power of 2

Given a number and check whether the number is a power of 2. There are different ways to find the solution, but I choose my own way to work on this.
First what I did here is find the square root of that number. Usually in C# Math.Sqrt(number), the number should be declared as double which means that number will have a decimal point ie, 4.0
After finding the square root, type cast the square root value to integer so that it removes the decimal portion completely.
If the number is power of 2, then square of type casts value will be same as the number to be checked or else the result will be false(as we removed the decimal portion of that number shows which is not power of 2).

//method for checking whether number is power of 2
 public void poweroftwo(double num)
        {
//get the square root of the number
            double val = Math.Sqrt(num);
//type cast the value to integer value
            int power = (int)val;
//check if the square of type casts value is equal to number to be checked
            if (power * power == num)
            {
                Console.WriteLine("Yes, the number is power of 2");
            }
            else
            {
                Console.WriteLine("Number not power of 2");
            }
         
       }

//Input number= 9
Output: Yes, the number is power of 2
//Input number=11
Output: Number not power of 2


No comments:

Post a Comment