Source of the topic:
https://leetcode.com/problems/number-of-1-bits/
The problem was discovered when the brush leetcode.
As a perennial run the bottom of the embedded I, for this topic interest is still very strong
classSolution { Public: intHammingweight (uint32_t N) {intCNT =0; for(intI=0;i< +; i++){ if((n& (1<<i))! =0) {CNT++; } } returnCNT; }};
The first way to think of this is this.
Then after running through 600 testcase is 13ms function no problem
Then I thought, if the number of bits is not much, there is a lot of redundancy calculation, so I changed this method.
classSolution { Public: intHammingweight (uint32_t N) {intCNT =0; while(n! =0) {CNT++; uint32_t tmp= ((n1) ^n) +1; if(TMP = =0) {n-=0x80000000; }Else{n-= tmp>>1; } } returnCNT; }};
This time is 10ms ... Well, it really didn't improve much.
Then I found out when I was talking to the group.
I was trapped in it. Because I need to pull out the last bit in the actual demand.
But there is no need to know this information in the actual subject.
And this method is fast mostly fast in
n=n& (n-1)
Just take care of the last bit and clear it.
So, the speed is 1 time times higher.
int Hammingweight (uint32_t N) { int cnt=0; while (n!=0) { cnt+ +; n=n& (n1); } return CNT;}
It's basically the end of the head.
But... The time of the lunatic space change is not yet useless.
Another way is to turn u32 into 4 U8 and then look up the table to add ...
Considering that it is not very practical, the actual speed does not necessarily have a great breakthrough. Not tangled up, later idle bored in the toss under
About u32 finding and locating last to bit number of 1 Bits