【LeetCode】190 & 191 - Reverse Bits & Number of 1 Bits
2015-08-04 00:06
597 查看
190 - Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Solution 1:
Solution 2:
191 - 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
Solution:n&(n-1)实现n与n-1的按位与,消除最后一位1
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Solution 1:
class Solution { public: uint32_t reverseBits(uint32_t n) { //runtime:4ms unsigned ret = 0; unsigned x = 1 << 31; unsigned y = 1; while(x){ if(x & n)ret |= y; //或ret += y; x >>= 1; y <<= 1; } return ret; } };
Solution 2:
class Solution { public: uint32_t reverseBits(uint32_t n) { //runtime:4ms unsigned int bit = 0; unsigned int result = 0; while(bit<32) { if((n>>bit) & 1 == 1) result = result + (1<<(31-bit)); bit ++; } return result; } };
191 - 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.
Solution:n&(n-1)实现n与n-1的按位与,消除最后一位1
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int count=0; 5 while(n){ 6 n &= (n-1); 7 count++; 8 } 9 return count; 10 } 11 };
相关文章推荐
- volley学习笔记(五):Android Volley框架的几种post提交请求方式
- 设备管理员(锁屏,回复出厂设置等功能)
- 健康不是第一,而是唯一!看完让你观念彻底改变!
- 设置myeclipse的默认jdk版本(导入jre system library)
- hd3635 Dragon Balls(之前题意翻译有误,已改正)
- HDU - 3572 Task Schedule (最大流)
- PHP微信支付开发实例
- wkhtmltopdf:一个 Linux 中将网页转成 PDF 的智能工具
- 自定义Android的EditText实现仿淘宝登录功能
- uva 10969
- 如何使用 pdfgrep 从终端搜索 PDF 文件
- 在Linux下如何修改Mysql的用户(root)的密码
- 详解ASP.NET七大身份验证方式以及解决方案
- 浅谈python多线程和队列管理shell程序
- python利用装饰器进行运算的实例分析
- Python实现字典的key和values的交换
- 使用python加密自己的密码
- python利用datetime模块计算时间差
- 合并百度影音的离线数据( with python 2.3)
- Python利用ansible分发处理任务