Number of 1 Bits
题目地址:
https://leetcode.com/problems/number-of-1-bits/#/description
题目:
解题思路:
这道题主要就是要用比特操作。
代码:
https://leetcode.com/problems/number-of-1-bits/#/description
题目:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.解题思路:
这道题主要就是要用比特操作。
代码:
public static int hammingWeight(int n) { int count = 0; for(int i = 0; i <= 31; i++){ count += ((n & 1) == 1) ? 1 : 0; n >>= 1; } return count; }

Comments
Post a Comment