Checks whether a positive integer is the nth power of 2.

Source: Internet
Author: User

Permission security and status-based ManagementProgramAnd found that numbers like Npower 2 are very useful. Because it is convenient for logical operations.

Sometimes it is necessary to verify whether a number is the n power of 2: I wrote a method today to find it very interesting. Of course, I am a cainiao, And the heroes saw it.

Static bool checknumifisnpoweroftwo (ulong num)

{

Console. writeline (datetime. Now. millisecond );

If (num = 0) return false;

Byte state = 0; // The value does not actually exceed 63

For (INT I = 0; I <64; I ++) // cyclically 64 times

{

If (Num-1 = (Num> = 1 ))

{State ++;

}

If (num = 1) break; // This loop determines whether the current bit is the same as the adjacent one on the left;

// When the frontend is the rightmost bit, the right shift operation actually fills in the symbol bit on the leftmost side (the unsigned value is 0, the signed value is 1, and here it is 0 ). Because 0 is supplemented, it is no longer the object we want to detect.

}

Console. writeline (datetime. Now. millisecond );

If (State = 1) return true;

Else return false;

}

It takes 3 ms to test uint. maxvalue.

Call

Ulong num = (ulong) uint. maxvalue + 1;
Console. writeline ("{0} is the Npower of 2? {1} ", num, checknumifisnpoweroftwo (Num ));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.