- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a number is a power of 2 in C#?
A power of 2 is a number of the form 2n where n is an integer
The result of exponentiation with number two as the base and integer n as the exponent.
n | 2n |
---|---|
0 | 1 |
1 | 2 |
2 | 4 |
3 | 8 |
4 | 16 |
5 | 32 |
Example 1
class Program { static void Main() { Console.WriteLine(IsPowerOfTwo(9223372036854775809)); Console.WriteLine(IsPowerOfTwo(4)); Console.ReadLine(); } static bool IsPowerOfTwo(ulong x) { return x > 0 && (x & (x - 1)) == 0; } }
Output
False True
Example 2
class Program { static void Main() { Console.WriteLine(IsPowerOfTwo(9223372036854775809)); Console.WriteLine(IsPowerOfTwo(4)); Console.ReadLine(); } static bool IsPowerOfTwo(ulong n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } }
Output
False True
- Related Articles
- Check if a number is a power of another number in C++
- Check if given number is a power of d where d is a power of 2 in Python
- Check if a number is power of 8 or not in C++
- Check if a number is power of k using base changing methods in C++
- Check if a number can be expressed as power in C++
- Write a C# program to check if a number is divisible by 2
- Number of pairs whose sum is a power of 2 in C++
- Check if a number is Palindrome in C++
- Check if a number is Bleak in C++
- Program to check a number is power of two or not in Python
- Check if a number is a Mystery Numbers in C++
- Check if a number is a Trojan Numbers in C++
- Check if a number is a Krishnamurthy Number or not in C++
- How to check if field is a number in MongoDB?
- Check if a number can be expressed as x^y (x raised to power y) in C++

Advertisements