Topic
Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011
has a binary representation, so the function should return 3.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Code 1. Recursive operation, although Leet does not pass because of the time reason
public class Solution { //need to treat N as a unsigned value public static int hammingweight (int n) { I F (n==0) return 0; if (n==1) return 1; int total=1; int index=1; while (n-total*2>=0) { total=total*2; } N=n-total; Index=index+hammingweight (n); return index; }
2. Using the bitwise Operation method
public class Solution { //need to treat N as a unsigned value public int hammingweight (int n) { if (n= =0) return 0; int i=0; while (n!=0) { n=n & (n-1); i++; } return i; }}
Code Download: Https://github.com/jimenbian/GarvinLeetCode
/********************************
* This article from the blog "Bo Li Garvin"
* Reprint Please indicate the source : Http://blog.csdn.net/buptgshengod
******************************************/
"Leetcode from zero single row" No 191.Number of 1 bits (study bit operation)