Compute how many bits to require convert one integer to another
来源:互联网 发布:mac win8压缩软件 编辑:程序博客网 时间:2024/06/04 09:01
Problem
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2
Input: 31, 14
Output: 2
Solution
using System;
namespace JamesChen
{
class BitDifference
{
static int CalculateBitDifference(int a, int b)
{
int count = 0;
a = a ^ b;
while (a != 0)
{
a &= (a - 1);
count++;
}
return count;
}
static void DoTest(int a, int b)
{
Console.WriteLine("a = {0, 4}, b = {1, 4}", a, b);
Console.WriteLine("{0, 32} -- a", Convert.ToString(a, 2));
Console.WriteLine("{0, 32} -- b", Convert.ToString(b, 2));
Console.WriteLine("requires {0} bit convert a to b",
CalculateBitDifference(a, b));
Console.WriteLine("-----------------------------------");
}
static void Main(string[] args)
{
DoTest(31, 14);
DoTest(14, 31);
DoTest(-2, 0);
DoTest(0, -2);
DoTest(-5, -20);
DoTest(-20, -5);
}
}
}
Output
a = 31, b = 14
11111 -- a
1110 -- b
requires 2 bit convert a to b
-----------------------------------
a = 14, b = 31
1110 -- a
11111 -- b
requires 2 bit convert a to b
-----------------------------------
a = -2, b = 0
11111111111111111111111111111110 -- a
0 -- b
requires 31 bit convert a to b
-----------------------------------
a = 0, b = -2
0 -- a
11111111111111111111111111111110 -- b
requires 31 bit convert a to b
-----------------------------------
a = -5, b = -20
11111111111111111111111111111011 -- a
11111111111111111111111111101100 -- b
requires 4 bit convert a to b
-----------------------------------
a = -20, b = -5
11111111111111111111111111101100 -- a
11111111111111111111111111111011 -- b
requires 4 bit convert a to b
-----------------------------------
Press any key to continue . . .
- Compute how many bits to require convert one integer to another
- Compute how many bits to require convert one integer to another
- How to convert an input image from one color space to another space
- another one: how to do research?
- How to define One-Many and One-One relationships
- How to move Oracle data from one machine to another
- How to compute the square root of an integer?
- How to do one-to-many video broadcast?
- Beginning MyBatis 3 Part 2 : How to Handle One-to-Many and One-to-One Selects
- How to convert List<Integer> to int[] in Java?
- <many to one>和<one to many>
- <many-to-one>和<one-to-many>
- hibernate many-to-one // one-to-many
- one word to another.
- [CrackCode] 5.5 Determine the number of bits required to convert integer A to integer B
- Ruby, how to shuffle one array into another
- nhibernate one to one,one to many
- one to many
- class_create
- SVN修改用户名与密码
- 收集的有关网络安全的常用链接
- ubuntu12.04 gvim启动慢解决办法
- postgreSQL学习记录之raise用法
- Compute how many bits to require convert one integer to another
- linux串口编程参数配置详解
- 直接插入排序与二分查找
- webbug 解决数据库乱码的问题
- 《Linux程序设计》读书笔记------第十一章 进程
- Linux输入子系统:事件的编码 -- event-codes.txt
- linux 压缩文件的命令总结
- 【转】Ubuntu安装PHP
- 输入n,输出对应的所有长度为n的二进制串