How to determine whether a number is a power of two without arithmetic operators?

Source: Internet
Author: User

This is the first blog post, and what I want to write is an algorithm that I learned today: no arithmetic operator is used to determine whether a number is a power of two;

public static  bool Poweroftwo (int x) {return (X & (x-1)) = = 0;}

X if the power of 2, then the X is converted into a binary number only the first is 1 other bits are 0 (4 100,8 1000 16 10000), then X-1 is a first 0 other bits are 1 of the number (3 011, 7 0111) This form of

If X is a power of 2 then X and (X-1) do with the value returned by the operation must be 0. This allows you to quickly determine whether a number is a power of 2.

Statistics attach code with complex methods

int fun (n) {/* input n, if it is an integer power of 2, 1 is returned, otherwise 0 */int M is returned; M=n;for (;;) {if (m== 1) return 1;if (m%2 = = 1) return 0ELSEM=M/2;}}

  

How to determine whether a number is a power of two without arithmetic operators?

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.