Flip Bits
来源:互联网 发布:网络直播都有什么内容 编辑:程序博客网 时间:2024/06/11 08:20
Determine the number of bits required to flip if you want to convert integer n to integer m.
Have you met this question in a real interview?Yes
Example
Given n = 31
(11111), m = 14
(01110), return 2
.
Note
Both n and m are 32-bit integers.
看到题目的第一想法是异或操作,c = a ^ b,然后右移求c的1的个数即为a,b不同的二进制位数,但是一提交不对,为什么呢?思路是对的,只是细节没有考虑清楚,假如a,b异号,那么c必然是小于0的数,然而对于一个小于0 的数执行右移操作会进入死循环,因为带符号的数右移会在右边补充符号位,而不是0。既然这样的话,-1右移会进入死循环;那怎么解决呢?貌似要分情况了,当a,b同号时,直接右移统计1的个数是没有问题的;当a,b异号时,则要求出c的源码,然后统计源码减1中0的个数,这次不是统计1,而是统计0了。另外还有一个细节需要记住,因为在补码的时候,是在原码的基础上取反,然后加了一个1,那为了跟补码的情况保持一致,必须讲原码减去一个1,这样0的个数才是原补码1的个数,这个细节非常重要。
class Solution {public: /** *@param a, b: Two integer *return: An integer */ int bitSwapRequired(int a, int b) { // write your code here int c = a ^ b; int count = 0, tmpc = c; if (c < 0) tmpc = ~(c - 1) - 1; while (tmpc) { int bit = tmpc & 0x1; count = bit ? count + 1 : count; tmpc >>= 1; } if (c < 0) return 32 - count; return count; }};
0 0
- Flip Bits
- lintcode: Flip Bits
- 位操作--- Flip Bits
- #181 Flip Bits
- LintCode Flip Bits 将整数A转换为B
- lintcode | 将整数A转换为B, Flip Bits
- flip
- flip
- 181.Flip Bits-将整数A转换为B(容易题)
- 比特位操作——Flip Bits(将整数A转化为B)
- Bits
- Bits*
- Flip-flop
- Flip coins
- Flip Game
- Flip Game
- Flip Game
- Flip Game
- 大讲台谈hive(初篇)
- 前端各种技术简介
- HDU 4497 GCD and LCM
- HDU 2899 Strange fuction
- powerDesigner自制的最简单的数据库表结构报告文档&表字段布局说明
- Flip Bits
- POJ 2247 Humble Numbers
- ExtJs 中 Ajax 连接超时设置与问题排查
- ARM汇编中的:比较指令--CMN / CMP / TEQ / TST
- 南邮 OJ 1356 方格取数问题
- iOS 知识点
- 单片机矩阵按键长短按
- Marquee Effect
- 大型网站核心架构要素