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. return与finally

    当return遇到了finally,先标记return的值,然后执行finally,当finally修改了return的值,那么执行finally后,传递最后一次return的值,若finally没有 ...

  2. servlet HttpSession 监听器

    一.Servlet中对象作用域 1. ServletContext 上下文 应用服务器一启动就产生该对象,服务器关闭即销毁 作用于全局,所有Servlet ,相当于静态变量 2. HttpSessio ...

  3. js实现FileUpload选择图片后预览功能

    当asp.net的FileUpload选择一个图片后不需要上传就能显示出图片的预览功能, 代码: <%@ Page Language="C#" AutoEventWireup ...

  4. MSSQL 各个发行版本版本号以及Compact 版本号

    终于开始写博客了. 不要笑啊. 下面是MSSQL 的发行版本以及版本号.自己整理的. http://support.microsoft.com/kb/321185/zh-cn SQL Server 2 ...

  5. linux下安装mysql5.6(官方文档)

    Using the MySQL Yum Repository  /  Installing MySQL on Linux Using the MySQL Yum Repository Chapter ...

  6. CI 自动操作日志

    在控制器中,继承一个总控制器,MY_Controller,让其他集成的控制器,继承my控制器 在MY_Controller控制器中,重写构造方法, 代码如下,测试pass! class MY_Cont ...

  7. python基础(目录)

    1.数据库操作入门 2.网络编程入门 3.编码规范 4.测试

  8. ES6学习笔记之Promise

    入职百度EFE团队实习已经三周了,实习中接触到了生产环境的技术和开发流程,大开眼界,和自己在学校接小作坊式项目是很不一样的体验.其中一个很大的感触是,ES6早已不是“选修”的尝鲜技术,而是已经全面普及 ...

  9. Linux Bash环境下单引(')、双引号(")、反引号(`)、反斜杠(\)的小结

    在bash中,$.*.?.[.].’.”.`.\.有特殊的含义.类似于编译器的预编译过程,bash在扫描命令行的过程中,会在文本层次上,优先解释所有的特殊字符,之后对转换完成的新命令行,进行内核的系统 ...

  10. ACM HDU 2674 N! Again(数论)

    继续数论.. Problem Description WhereIsHeroFrom:            Zty,what are you doing ? Zty:                 ...