Problem:

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.

Analysis:

This problem is like a magic, it could teach you a mgic skill in bit operation.

The instant idea:
Let us count the bit one by one, the easy way is to use a dividend (initial value is 2^31).
Theoretically, all integer could be represented in the form :
digit(31)*2^31 + digit(30)*2^30 + digit(29)*2^29 + ...
It could be solved by following pattern.
Assume: dividen = 2^i
digit = n / dividen (n is no larger than 2^(i+1))
The digit is the digit at 'i' index.
For next index, we need update dividen
dividen = dividen / 2; However that's just theoretical way!!!-.- Wrong solution: public int hammingWeight(int n) {
int count = 0;
long dividen = 1;
int digit = 0;
for (int i = 0; i < 31; i++)
dividen = dividen * 2;
while (n != 0) {
digit = n / dividen;
if (digit == 1)
count++;
n = n % dividen;
dividen = dividen / 2;
}
return count;
}
Wrong case:
Input:
1 (00000000000000000000000000000001)
Output:
0
Expected:
1 Reason:
For ordinary integer, it has reserved one bit for indicate 'negative' or 'positive' of a number. Only 31 bit could be used for representing digits.
Positive Range: [0, 2^31-1]
Negative Range: [-1, -(2^31)]
Why negtaive could reach 2^31, cause for "0000...000", it is no need for representing '-0', thus we use it for representing '-(2^31)'. Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html Thus the following code could exceed range of positive number.
----------------------------------------------------------------------
for (int i = 0; i < 31; i++)
dividen = dividen * 2;
---------------------------------------------------------------------- A magic way to solve this problem:
Skill:
How to wipe out the last '1' of a integer?
n = n & (n-1)
Reason:
n-1 would turn the last '1' into '0', and all '0' after it into '1'.
Then we use '&', to keep recovering all bits except the last '1'. (has already been changed into '0')
Case:
n = 11110001000
&
n - 1 = 11110000000
ans = 11110000000 Great! Right! Don't mix this skill with
n = n ^ (n-1)
Which could keep the rightmost '1' bit only, all other bit were set into '0'.
Reference:
http://www.cnblogs.com/airwindow/p/4765145.html

Solution:

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n-1);
}
return count;
}
}

[LeetCode#191]Number of Bits的更多相关文章

  1. C#版 - Leetcode 191. Number of 1 Bits-题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  2. Leetcode#191. Number of 1 Bits(位1的个数)

    题目描述 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量). 示例 : 输入: 11 输出: 3 解释: 整数 11 的二进制表示为 000000 ...

  3. LN : leetcode 191 Number of 1 Bits

    lc 191 Number of 1 Bits 191 Number of 1 Bits Write a function that takes an unsigned integer and ret ...

  4. LeetCode 191. Number of 1 bits (位1的数量)

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...

  5. [LeetCode] 191. Number of 1 Bits 二进制数1的个数

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...

  6. LeetCode 191 Number of 1 Bits

    Problem: Write a function that takes an unsigned integer and returns the number of '1' bits it has ( ...

  7. Java for LeetCode 191 Number of 1 Bits

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...

  8. (easy)LeetCode 191.Number of 1 Bits

    Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1' bits ...

  9. Java [Leetcode 191]Number of 1 Bits

    题目描述: Write a function that takes an unsigned integer and returns the number of ’1' bits it has (als ...

随机推荐

  1. Linux查看当前系统登录用户、登录日志、登录错误日志

    1.查看当前系统的登录用户 w who 2.查看成功登录历史记录 last -n 3.查看尝试登录失败的历史记录 lastb -n 4.显示每个用户最近一次登录成功的信息 lastlog

  2. maven 创建web项目

    1,新建一个web项目 2,构建基础目录 web.xml <!DOCTYPE web-app PUBLIC  "-//Sun Microsystems, Inc.//DTD Web A ...

  3. 排序算法(冒泡,选择,快速)Java 实现

    冒泡 排序: public static void Bubblesort(int [] a) { for(int x=0;x<=a.length-1;x++) { for(int y=0;y&l ...

  4. ca-bundle.crt to java truststore(e.g. trustStore.jks)

    1. download java keyutilhttps://java-keyutil.googlecode.com/files/keyutil-0.4.0.jar 2. run the follo ...

  5. js获取当前url参数

    //抓取url参数 function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theReque ...

  6. Java文件File操作一:文件的创建和删除

    一.简述 File 文件类,主要对文件进行相关操作.常用的File操作有:文件(夹)的创建.文件(夹)的删除,文件的读入和下载(复制)等: 二.文件(夹)的创建和删除 1.创建过程 实例: //cre ...

  7. [转]python pickle包,cPickle包 存储

    在之前对Python对象的介绍中 (面向对象的基本概念,面向对象的进一步拓展),我提到过Python“一切皆对象”的哲学,在Python中,无论是变量还是函数,都是一个对象.当Python运行时,对象 ...

  8. hibernate映射

    三种方式:     持久化注解   目前开发主流方式     XML配置描述文件(XML deployment descriptor,可以让Hibernate的PO类与JPA实体类兼容,实际中很少用) ...

  9. swift官方文档中的switch中case let x where x.hasSuffix("pepper")是什么意思?

    在官方文档中,看到这句.但不明白什么意思. let vegetable = "red pepper" switch vegetable { case "celery&qu ...

  10. C# 数据结构 基础 论述

    问题: 信息世界中,计算机是加工处理的信息的载体,在这个过程中面临着三个问题: 1.如何方便高效的组织数据 2.如何在计算机中存储数据(内存和外存) 3.如何对存储的数据进行高效的操作 目的: 我们都 ...