Leetcode 191 Number of 1 Bits

Source: Internet
Author: User

Leetcode 191 Number of 1 Bits

Solution One (more traditional method): Use to move N to the right, and with 1 think & get 1 of the number; (There is also the use of division/2, obvious division operation efficiency is lower than the displacement)

Time complexity: 0 (LOGN)

1 intHammingweight (uint32_t N) {2     intCount=0;3     4      while(n!=0) {5         if(N &1) {6++count;7         }8n = n>>1;9     }Ten      One     returncount; A}

Solution Two:

Methods of using n& (n-1)

Supposing n =0x110101

N n-1 n& (n-1)

step1:110101 110100 110100

step2:110100 110011 110000

step3:110000 101111 100000

step4:100000 011111 000000

It is found that several 1 n& (n-1) get 0, which is significantly more efficient than the previous ones.

Time complexity: O (M), M is the number of 1 in N.

The code is as follows:

1 intHammingweight (uint32_t N) {2     intCount=0;3     4      while(n!=0) {5count++;6n = n& (n1);7     }8     9     returncount;Ten}

Leetcode 191 Number of 1 Bits

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.