Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 76b9be1

Browse files
author
Ram swaroop
committed
flipping/inverting bits done
1 parent 16b0675 commit 76b9be1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package me.ramswaroop.bits;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 6/5/15
8+
* @time: 3:50 PM
9+
*/
10+
public class FlippingBits {
11+
12+
/**
13+
* Returns the number by flipping/inverting its bits using
14+
* XOR operation with 1......11 (size of int i.e, 32 1's).
15+
*
16+
* @param n
17+
* @return
18+
*/
19+
public static int getNumberByFlippingBits(int n) {
20+
return n ^ 0xffffffff; // equivalent to 11....1 (32 times) in binary
21+
}
22+
23+
/**
24+
* Returns the number by flipping/inverting its bits using
25+
* the NOT operator.
26+
*
27+
* @param n
28+
* @return
29+
*/
30+
public static int getNumberByFlippingBits_V1(int n) {
31+
return ~n;
32+
}
33+
34+
public static void main(String a[]) {
35+
System.out.println(getNumberByFlippingBits(5));
36+
System.out.println(getNumberByFlippingBits_V1(5));
37+
}
38+
}
39+
40+
/**
41+
* EXPLANATION:
42+
*
43+
* For input: 5
44+
*
45+
* Binary: 000.....101
46+
* Inverted: 111.....010 (which is the 2's compliment of -6)
47+
*
48+
* Therefore, result is -6.
49+
*/

0 commit comments

Comments
 (0)