[leetcode] Number of 1 Bits
2015-05-28 19:59
316 查看
From : 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
so the function should return 3.
Better Solution:
This is based on bit-manipulation, referenced by Dora' notes.
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.
class Solution { public: int hammingWeight(uint32_t n) { int count = 0; while(n) { count += n&1; n >>= 1; } return count; } };
Better Solution:
This is based on bit-manipulation, referenced by Dora' notes.
class Solution { public: int hammingWeight(uint32_t n) { n = ((0xAAAAAAAA&n)>>1)+(0x55555555&n); n = ((0xCCCCCCCC&n)>>2)+(0x33333333&n); n = ((0xF0F0F0F0&n)>>4)+(0x0F0F0F0F&n); n = ((0xFF00FF00&n)>>8)+(0x00FF00FF&n); n = ((0xFFFF0000&n)>>16)+(0x0000FFFF&n); return n; } };
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { n = ((n & 0xAAAAAAAA) >>> 1) + (n & 0x55555555); n = ((n & 0xCCCCCCCC) >>> 2) + (n & 0x33333333); n = ((n & 0xF0F0F0F0) >>> 4) + (n & 0x0F0F0F0F); n = ((n & 0xFF00FF00) >>> 8) + (n & 0x00FF00FF); n = ((n & 0xFFFF0000) >>> 16) + (n & 0x0000FFFF); return n; } }
相关文章推荐
- C# 网页画图
- 阅读《构建之法》第8,9,10章
- 百度相册提取器(Python)
- 一道递归题
- 注册界面的设计与实现
- 分类UIView+Extension:frame直接赋值方法
- hdu 2031(进制转换升级版)
- 原型模式
- 题目1521:二叉树的镜像
- 自动化测试入门指南(1)-- 概述
- java ExecutorService.invokeAny()和ExecutorService.invokeAll()的使用剖析
- linux下查看监听端口对应的进程
- 用Xcode6进行ios开发中,修改模拟器键盘显示中文
- Android开发面试经——6.常见面试官提问Android题②(更新中...)
- Android开发面试经——5.常见面试官提问Android题①
- CS小分队第二阶段冲刺站立会议(5月28日)
- 马哥教育第二十三MySQL基础应用入门
- POJ2153-map
- 多线程实现简单的一对一聊天
- javaWeb笔记--虚拟主机以及虚拟目录映射的配置