

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Check if given number is a power of d where d is a power of 2 in Python
- Check if a number is a power of another number in C++
- Check if a number is power of 8 or not in C++
- Nearest power 2 of a number - JavaScript
- 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 power of k using base changing methods in C++
- Checking if a number is a valid power of 4 in JavaScript
- Check if a number can be expressed as power in C++
- Check if n is divisible by power of 2 without using arithmetic operators in Python
- Checking if a number is some power of the other JavaScript
- How to check if field is a number in MongoDB?
- Program to check a number is power of two or not in Python
- Check if a number can be expressed as 2^x + 2^y in C++
- Compute modulus division by a power-of-2-number in C#
Advertisements