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. oracle 11g 报错记录

    1.ORA-01034: ORACLE not available sqlplus "sys/password as sysdba" 2.ORA-00119: invalid sp ...

  2. not exists 跟not in 纪念一下

  3. jquery ajax获取和解析数据

    最近项目中用到了ajax技术,之前虽然写过一点点,但是没有系统的总结过.趁着刚刚用过,手热就记录一下,方便以后查阅. $.ajax中的参数 $.ajax的函数格式: $.ajax({ type: 'P ...

  4. C#设置与获取目录权限(.net控制ACL)

    找到两种方式可以修改文件夹的权限 第一种: 想用c#来设置和读取ntfs分区上的目录权限,找了很多资料,未果.终于发现了一段vb.net的代码,做了修改,以C#展示给大家. using System; ...

  5. 关于Androdi中SQLITE 3采用GBK编码存储,数据库中文乱码问题。

    1.最近开发一个项目,用SQLite Expert Personal打开数据库如下图,title会产生乱码,问题. 2.由于SQL lite默认是存储UTF-8格式,后来更改数据库编码类型为ANSI, ...

  6. Oracle计算时间函数(numtodsinterval、numtoyminterval)

    numtodsinterval(<x>,<c>) ,x是一个数字,c是一个字符串,表明x的单位,这个函数把x转为interval day to second数据类型 常用的单位 ...

  7. CSS Positioning(定位)

    Positioning(定位) CSS定位属性允许你为一个元素定位.它也可以将一个元素放在另一个元素后面,并指定一个元素的内容太大时,应该发生什么. 元素可以使用的顶部,底部,左侧和右侧属性定位.然而 ...

  8. string的一些更改发

    /* String 类:  1.1字符串的长度    int c =对象.length();  1.2字符串某个字符的位置  int index=对象.indexOf("字母")  ...

  9. Windows phone 之独立存储

    独立存储命名空间的说明:

  10. 两个winform窗体同步

    /// <summary>        /// 初始left距离        /// </summary>        int initx = 0;        /// ...