Csapp (1): computer representation of numbers--after-school questions

Source: Internet
Author: User

2.65

int even_ones (unsigned x)

Requirements: Return 1 when x contains an even number of 1s; 0 otherwise. Suppose an int has a w=32 bit.

Analysis: The most expected use is a loop, but the loop statement cannot be used. If one is written in a statement, it takes 32 times; Here the dichotomy is used, then the operation becomes Log232 = 5 times. The dichotomy implies a loop and simplifies the loop traversal. How to use the dichotomy method?

The title is to Judge X 1 of the odd even, you can divide X into 2, the first 16 X1 and the last 16 x2,x3=x1^x2, if X has an even number of 1,x3 must have an even number of 1, if X has an odd number of 1,x3 must have an odd number.

int even_ones (unsigned x) {     +);      8 );      4 );      2 );      1 );      return 1 );    }

2.66

int Leftmost_one (unsigned x)

Requirements: Generate mask indicating leftmost 1 in X. assume w=32; If x=0, then return 0;

Tip: First convert the x into a bit vector like [0..011..1]

Analysis: Here is the first place to look for the top 1 bit vector x which is the number one, should use loops, and then the loop cannot be used, here is the dichotomy. First, for example, the X is transformed into a bit vector such as [0..011..1], i.e. all bits after the highest bit 1 become 1.

int leftmost_one (unsigned x) {     1;      2 ;      4 ;      8 ;       - ;      1 );      return x;}

Csapp (1): computer representation of numbers--after-school questions

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.