Determines whether a number is a power of 2

Source: Internet
Author: User
Tags bool

Given an integer n, determine if it is a power of 2.

Idea: 2,4,8,16,32 .... are 2 of the power of n times

Conversions to binary are:

10 100 1000) 10000 100000

These numbers minus 1 after the bitwise and with themselves, if the result is 0, indicating that the number is 2 of the power of N

01 011 0111) 01111 011111


10&01 = 0 100&011 = 0 1000&0111 = 0 10000&01111 = 0 100000&011111 = 0


Source:

#include <stdio.h>/

* Determines whether an integer is a power of 2 *
/bool Fun (int v)
{
	bool flag = 0;
	if ((v>0) && (v& (V-1)) ==0)
		flag = 1;
	return flag;
}

int main (void)
{
	int A;
	printf ("Please enter a 32-bit integer:");
	scanf ("%d", &a);
	if (fun (a))
		printf ("This number is 2 power \ n");
	else
		printf ("This number is not 2 power \ n");
	return 0;
}
Execution Result:



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.