careercup5.5求解转换两数所需修改的位数
2013-05-10 15:16
302 查看
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2
首先利用xor异或运算算出两数不同的位数,假设输入的两数为a,b,X=a^b,X中含有的1的位数即为要求的值
为了求出X中1的位数,可以每次把X与1进行and(&)操作,累加低位的1,然后把低位1累加之后对X进行右移操作。
Input: 31, 14
Output: 2
首先利用xor异或运算算出两数不同的位数,假设输入的两数为a,b,X=a^b,X中含有的1的位数即为要求的值
为了求出X中1的位数,可以每次把X与1进行and(&)操作,累加低位的1,然后把低位1累加之后对X进行右移操作。
#include<iostream> using namespace std; int diff_bits(int a,int b){ int count=0; for(int i=a^b;i>0;i>>=1){ //每次累加低位的1,如果低位数字为1的话 count+=i&1; } return count; } int main(){ cout<<diff_bits(31,14)<<endl; //for test system("pause"); return 0; }
相关文章推荐
- [CareerCup] 5.5 Number of Converted Bits 转换数字所需的位数
- careercup5.5
- Hard 随机选择subset @CareerCup
- Hard 不用+号实现两个数之和 @CareerCup
- Linux下MySQL 5.5/5.6的修改字符集编码为UTF8
- PHP基础系列之字符串——存取和修改字符串中的字符、字符串的运算、字符串转换为数字
- 第一站NO.4--《C Primer Plus(第五版)中文版》第五章_5.4 运算符、表达式和语句和5.5 类型转换
- mysql 5.5 乱码问题,永久修改为utf8编码
- Arrays_Strings 90度顺时针逆时针旋转方形矩阵 @CareerCup
- LinkLists 乱序链表中移除重复的项 @CareerCup
- LinkLists 删除链表中的一个给定指针的结点 @CareerCup
- CareerCup Binary Tree the Maximum of 人
- CareerCup Randomly return a node in a binary tree
- 修改tflearn包中classification_report精确度位数
- CareerCup Facebook Alex moving on a table
- 修改驱动程序,解决“inf文件中找不到所需的段落”的问题
- C语言进阶-第6讲:递归法问题求解(两数的最大公约数)
- Careercup - Facebook面试题 - 5733320654585856
- CareerCup Given a dictionary, how would you add spaces in this string
- 安卓开发——百度地图修改地图中心点为所需经纬度以及地图空白的问题