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