【191】Number of 1 bits

题目

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

解法

思路一

这道题有一个非常取巧的解法,在java语言中 Integer类中提供了一个方法叫做 Integer.bitCount

它的主要作用就是用于统计参数n转成2进制后有多少个1,也就是说,只需要一行代码就可以搞定

public static int hammingWeight(int n) {
   return Integer.bitCount(n);
}

当然,如果有一天面试官问你这个问题的时候你这样解答错是没有错,但肯定不是他想要的答案,于是乎,你应该搬出这个方法的源码和他聊一聊,具体代码也不是很难,主要是一些进制转换和位运算的知识,jdk源代码如下:

 public static int bitCount(int i) {
        // HD, Figure 5-2
        i = i - ((i >>> 1) & 0x55555555);
        i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
        i = (i + (i >>> 4)) & 0x0f0f0f0f;
        i = i + (i >>> 8);
        i = i + (i >>> 16);
        return i & 0x3f;
 }

除此之外,你还应该提供给他一个自己的实现方案

思路二

首先我们可以确定,如果一个整数不为0,那么这个整数至少有一位会是1,如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话),其余所有位将不会受到影响

 public static int hammingWeight2(int n) {
    int count = 0;
    while (n != 0) {
        count++;
        n = (n - 1) & n;
    }
    return count;
}

思路三

用flag来与n的每位做位于运算,来判断1的个数

 public int hammingWeight3(int n) {
    int count = 0;
    int flag = 1;
    while (flag != 0) {
        if ((flag & n) != 0) {
   			count++;
        }
        flag = flag << 1;
   }
   return count;
}

Github地址:https://github.com/Bylant/LeetCode

CSDN地址:https://blog.csdn.net/ZBylant
微信公众号 在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值