forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert Integer A to Integer B.java
More file actions
executable file
·50 lines (38 loc) · 1.12 KB
/
Convert Integer A to Integer B.java
File metadata and controls
executable file
·50 lines (38 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
E
1522132721
tags: Bit Manipulation
把Integer A 转换成 Integer B 需要改变多少bits?
#### Bit Manipulation
- a^b 显示出bit format里面有不同binary code的数位.
- 每次 (a^b)>>i 移动i位之后, 再 & 1时其实是指留下这一位的数字.
- count
- 其实用到了 ^ 找不同的bit, >> 移位, &1 mask
```
/*
LintCode
Determine the number of bits required to convert integer A to integer B
Example
Given n = 31, m = 14,return 2
(31)10=(11111)2
(14)10=(01110)2
Tags Expand
Cracking The Coding Interview Bit Manipulation Binary Representation
Thinking process:
Assume the integer is 32 bit.
XOR a and b, shift by 1 bit everytime -> want to check the XORed value at index 0 : just & 1 will do.
Count the above calculated result: how many bit difference do a and b have.
*/
class Solution {
/**
*@param a, b: Two integer
*return: An integer
*/
public static int bitSwapRequired(int a, int b) {
int count = 0;
for (int i = 0; i < 32; i++) {
count += (a ^ b) >> i & 1;
}
return count;
}
};
```