Home c# How to check whether a given number is the degree of twos?

How to check whether a given number is the degree of twos?




How to check whether a given number is the degree of twos.

For example:

256 = 2 ^ 8

8 = 2 ^ 3

How can I implement this in C #?

Answer 1, Authority 100%

Another Classic Method :

n & gt; 0 & amp; & amp; (N & amp; (n - 1)) == 0

There is still a lot of all bit tricks on the link.

How does this trick work? That’s how. We write the number N in the binary system, and consider the rightmost unit in the binary representation of the number N . In the number N - 1 will be on the spot of this unit zero, and on the right of it units:

n: xxxxxx1000
1: 0000000001.
N - 1: xxxxxx0111

And the remaining binary numbers (designated as X ) will not change. Therefore, after the operation & amp; , it turns out that:

n & amp; (n-1): xxxxxx0000

This number will be zero if and only when, when all XXXXXX are zero. The only case where our consideration does not pass – the number 0: there is no “right” units at all, so this case has to be considered separately.

Interestingly, GCC and Clang give to this code and code from the answer @aepot strictly the same assembler code: https: //godbolt.org/z/xwx1qt

Answer 2, AUTHORITY 60%

There is a simple arithmetic way.

Private Bool ISPOWEROFTWO (Int Number)
  For (int x = 1; x & lt; = number; x * = 2)
    if (X == Number) Return True;
console.writeline (ISPOWEROFTWO (256));

But nevertheless, the questions about two always comes the best answer (usually) binary arithmetic and some knowledge of how numbers are stored in a binary form.

Private Bool ISPOWEROFTWO (Int Number)
  RETURN NUMBER & GT; 0 & amp; & amp; (Number & amp; -Number) == Number;

Answer 3

var num = 16;
var log = math.log2 (NUM);
If (log - math.truncate (log)! = 0)
  System.Console.WriteLine ($ "{num} is not a power of 2.");

But here it lies a lot of problems.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions