Data Structure-algorithm (015) (evaluate the number of 1 in integer binary representation)

Source: Internet
Author: User

[Statement: This article is only intended for self-Summary and mutual communication, and may be omitted. Email: Mr_chenping@163.com]

Question:

Enter an integer. Calculate the number of 1 in the Binary Expression of the integer. For example, input 10. Because the Binary Expression is 1010 and there are two 1 s, Output 2.

Question Analysis:

Solution 1: calculate the number of BITs as 1 from the right: Use the right shift operator to first determine whether the rightmost operator is 1 and then shift one to the right. It repeats until the input value changes to 0.

Solution 2: calculate the number of BITs as 1 from the left side. Another idea is that if an integer is not 0, at least one of the integers is 1. If we subtract 1 from this integer, the first 1 on the rightmost side of the integer will become 0, and the first 0 after 1 will become 1. All other bits will not be affected

Algorithm Implementation:

# Include

 
  
/*** Calculate the number of bits 1 from the rightmost */int count_bit_1 (int m) {int count = 0; while (m) {if (m & 1) count ++; m = m> 1;} return count ;}/ *** calculate the number of bits 1 from the leftmost */int count_bit_2 (int m) {int count = 0; while (m) {count ++; m = (m-1) & m;} return count ;} int main (int argc, char * argv []) {int m = atoi (argv [1]); printf ("% d -- method one ---> % d \ n", m, count_bit_1 (m); printf ("% d -- method two ---> % d \ n", m, count_bit_2 (m); return 0 ;}

 


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.