"Simple Algorithm" 44. Number of bits 1

Source: Internet
Author: User

Topic:

Write a function that the input is an unsigned integer that returns the number of digits in the binary expression as '1'3  000000000000000000000000000010112 1   00000000000000000000000010000000

Problem Solving Ideas:

1. Direct displacement can be shifted to the right 32 times, each time to determine whether the last one is 1;

The code is as follows:

classSolution { Public:    intHammingweight (uint32_t N) {intCount =0;  while(n!=0){            if(n&0x1==1) {Count++; } N= n>>1; }                returncount; }};

2. Observing N&n-1, one 1 will be eliminated.

class Solution {public:    int  hammingweight (uint32_t N) {        int  0;                  while (n!=0) {           ret++           ; = n& (n1);        }                 return ret;    }};

"Simple Algorithm" 44. Number of bits 1

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.