题目描述

image.png

解题思路

求所有位数是否为一,那么就依次移动二进制数,往右移动,各位数是1,计数器加一,知道这个数被移动为0。
特别注意:这里的n移动需要是>>>,而不是>>,>>>是无符号移动,该数可能为负数,也就是符号位可能为1,所以需要将符号位一起移动。

  1. public class Solution {
  2. // you need to treat n as an unsigned value
  3. public int hammingWeight(int n) {
  4. int count = 0;
  5. while (n != 0) {
  6. if ((n & 1) == 1) count++;
  7. n >>>= 1;
  8. }
  9. return count;
  10. }
  11. }

338. 比特位计数

和这道题类似,只不过这道题没有负数,移位也不需要考虑符号位,所以更简单!!!

  1. class Solution {
  2. public int[] countBits(int n) {
  3. int[] array = new int[n + 1];
  4. array[0] = 0;
  5. for (int i = 1; i <= n; i++) {
  6. int count = 0;
  7. int temp = i;
  8. while (temp != 0) {
  9. if ((temp & 1) == 1) count++;
  10. temp >>= 1;
  11. }
  12. array[i] = count;
  13. }
  14. return array;
  15. }
  16. }