[CrackCode] 5.5 Determine the number of bits required to convert integer A to integer B
2014-02-05 06:23
531 查看
Write a function to determine the number of bits required to convert integer A tointeger B
Input: 31, 14Output: 2
=========
Analysis:
Basic idea of mine is to compare each digits between A and B, and count the different times.
Another ides (from the book) is to use XOR between A and B. Result of which stores all the different digits. Then we can simply count the '1' digits in the result.
Input: 31, 14Output: 2
=========
Analysis:
Basic idea of mine is to compare each digits between A and B, and count the different times.
public class Answer { public static int countDiff(int a, int b){ int count = 0; int index = 0; if(a<0 || b< 0) return -1; while(index<32){ if(((1<<index)&a) != ((1<<index)&b)) count++; index++; } return count; } public static void main(String[] args) { int a = 217; int b = 532; System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); int nbits = countDiff(a, b); System.out.println("Required number of bits: " + nbits); } }
Another ides (from the book) is to use XOR between A and B. Result of which stores all the different digits. Then we can simply count the '1' digits in the result.
public class Question { public static int bitSwapRequired(int a, int b) { int count = 0; for (int c = a ^ b; c != 0; c = c >> 1) { count += c & 1; } return count; } public static void main(String[] args) { int a = 217; int b = 532; System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); int nbits = bitSwapRequired(a, b); System.out.println("Required number of bits: " + nbits); } }
相关文章推荐
- 分享个上传插件plupload的queue美化版 版本是 2.1.2
- USACO 2009 Feb Cruel Math Teacher 数的幂次
- easy ui实现行编辑的treegrid——etreegrid
- 改变UITabBarController选中的View Controller
- VS异常--未找到与约束 ContractName Microsoft.VisualStudio.Language.Intellisense.IGlyphService RequiredTypeIdentity
- UIScrollview要加载大量数据的时候,考虑到内存的消耗问题,我们不可能全部加载完。
- 《APUE》Chapter 3 File I/O(学习笔记加上自己的代码)
- 黑马程序员_19GUI简述
- perl hash 按value/按keys 排序(多种方法)
- UVa 123 - Searching Quickly解题报告
- Java SE 12_Frequently-used Class Library(2)
- CompareText 比较两个字符串的ordinal value,不区分大小写
- Request.url请求路径的一些属性
- UiButton操作
- UI组件缩放和旋转
- IOS之UI添加动画
- USACO Sorting a Three-Valued Sequence
- iOS——UIActivityIndicatorView活动指示器
- Maven 构建(Build)项目
- easyui 分页保存checkbox的选中状态