191. 位1的个数

描述

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。

链接

191. 位1的个数 - 力扣(LeetCode) (leetcode-cn.com)

剑指 Offer 15. 二进制中1的个数 - 力扣(LeetCode) (leetcode-cn.com)

 

解法一: 逐位判断

  • 若 n \& 1 = 0n&1=0 ,则 nn 二进制 最右一位 为 00 ;
  • 若 n \& 1 = 1n&1=1 ,则 nn 二进制 最右一位 为 11 。
 1 public class Solution {
 2     // 注意这里的 n 是 二进制下的 n,即 101 其值为 5(sout的时候)
 3     public int hammingWeight(int n) {
 4         int res = 0;
 5         while ( n != 0) {
 6             res += n & 1; // 也可以计数
 7             n = n >>> 1;
 8         }
 9         return res;
10     }
11 }

 

 解法二:根据 消去 最右边的 1 进行计数,采用 n & (n - 1)

  • (n−1)  解析: 二进制数字 n 最右边的 1 变成 0 ,此 1 右边的 0 都变成 1 。
  • n & (n - 1)  解析: 二进制数字 n 最右边的 1 变成 0 ,其余不变。

 

 

 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int res = 0;
 5         // n = n & (n - 1) 代表消除 右往左第一个 数字1
 6         // 每消除 一次 就计数 +1
 7         while (n != 0) {
 8             res++;
 9             n = n & (n - 1); 
10         }
11         return res;
12     }
13 }

 

 

参考

二进制中1的个数 - 力扣(LeetCode) (leetcode-cn.com)

posted @ 2021-11-30 19:58  DidUStudy  阅读(39)  评论(0编辑  收藏  举报