C. Some classic operations

Source: Internet
Author: User

1: Evaluate the return value of the following function -- count the number of 1 ---- meaning of the x & (x-1) Expression

[Cpp]
Int func (int x)
{
Int countx = 0;
While (x)
{
Countx ++;
X = x & (x-1 );
}
Return countx;
}

 

Assume x = 9999
10011100001111
Answer: 8

Train of Thought: Convert x to a binary system and check the number of contained 1.
Note: each time x = x & (x-1) is executed, a 1 on the rightmost side of x is changed to 0 when x is represented in binary, because the X-1 will change this bit (A 1 on the rightmost when x is represented in binary) to 0.

 


2: Determine whether a number (x) is the N power of 2.

[Cpp]
# Include <stdio. h>
 
Int func (int x)
{
If (x & (x-1) = 0)
Return 1;
Else
Return 0;
}
 
Int main ()
{
Int x = 8;
Printf ("% d \ n", func (x ));
}

 

 


Note:
(1) If a number is the N power of 2, the highest bit of this number is 1 in binary format, and the rest is 0.

(2) = the priority is higher &



From the SongCdut Column

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.