[leetcode]Number of 1 Bits
2015-12-09 22:13
344 查看
题目描述如下:
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.
显然是求解一个整数的二进制表示法中有几个1,自然想到一位一位向右位移,数出1的个数(这里要注意,加入用的是Java,Java中的int是有符号的,也就是说32bit里还包含负数,输入2147483648时超出输入参数的范围)。
在网上看到另一种算法,拉过来学习一下:
假设n= 1111000111000 那 n-1 = 1111000110111, (n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说, (n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比下面的快了。有几个1,执行几次。
代码如下:
题目链接:https://leetcode.com/problems/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).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
显然是求解一个整数的二进制表示法中有几个1,自然想到一位一位向右位移,数出1的个数(这里要注意,加入用的是Java,Java中的int是有符号的,也就是说32bit里还包含负数,输入2147483648时超出输入参数的范围)。
在网上看到另一种算法,拉过来学习一下:
假设n= 1111000111000 那 n-1 = 1111000110111, (n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说, (n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比下面的快了。有几个1,执行几次。
代码如下:
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; while(n != 0){ n = n & (n - 1); count ++; } return count; } }
题目链接:https://leetcode.com/problems/number-of-1-bits/
相关文章推荐
- 搜集的一些关于MQTT的资料
- Oralce lock机制解析
- Effective C++阅读笔记_条款2:尽量以const,enum,inline替换#define
- 实验二
- 基于缺陷分布的质量目标分解和质量预测体系
- 用FragmentActivity实现点击跳转Fragment效果(未完)
- mfc 模仿键盘按键向银行密码控件输入密码
- ArrayList、Vector、LinkedList的区别及其优缺点?
- 如何使用vs对程序进行打包?怎么通过注册表获取安装路径?
- 自我简介
- 实验四
- logstash 输出到elasticsearch 自动建立index
- 【iCore3 双核心板】例程十:RTC实时时钟实验——显示日期和时间
- 动态规划 - 最长公共子序列(LCS)
- 变量,常量,引用类型,值类型,枚举类型, 值类型和引用类型的简单区别,类型转换,装箱与拆箱
- tableView的重用机制
- iOS 推送 通知 测试
- windows下安装配置apache、mysql、php
- Android studio安装和一些快捷键
- 实验五