Skip to content

Commit 92b90bf

Browse files
committed
xor without xor
1 parent 2a41500 commit 92b90bf

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
- [x] [Bit Hacks — Part 3 (Playing with rightmost set bit of a number)](http://www.techiedelight.com/bit-hacks-part-3-playing-rightmost-set-bit-number/)
5959
- [x] [Bit Hacks — Part 4 (Playing with letters of English alphabet)](http://www.techiedelight.com/bit-hacks-part-4-playing-letters-english-alphabet/)
6060
- [x] [Bit Hacks — Part 5 (Find absolute value of an integer without branching)](http://www.techiedelight.com/bit-hacks-part-5-find-absolute-value-integer-without-branching/)
61-
- [ ] [Bit Hacks — Part 6 (Random Problems)](http://www.techiedelight.com/bit-hacks-part-6-random-problems/)
61+
- [x] [Bit Hacks — Part 6 (Random Problems)](http://www.techiedelight.com/bit-hacks-part-6-random-problems/)
6262

6363
## Algorithms
6464

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package binary.xorFinder;
2+
3+
// Given two integers, find their XOR without using the XOR operator.
4+
// (x | y) - (x & y) is equivalent to x ^ y
5+
// XOR sets the bits in either num
6+
// then unsets the ones both have
7+
8+
// e.g. 01000001 XOR 01010000 :
9+
// set all: 01010001
10+
// ^ ^ ^
11+
// (S1, S2) S1 S2
12+
// now unset common aka leftmost set: 00010001
13+
14+
import utils.InputReader;
15+
16+
public class FindXORWithoutXOR {
17+
public static void main(String[] args) {
18+
System.out.println("Number 1: ");
19+
int x1 = InputReader.readInt();
20+
System.out.println("Number 2: ");
21+
int x2 = InputReader.readInt();
22+
System.out.println("N1 in binary: " + Integer.toBinaryString(x1));
23+
System.out.println("N2 in binary: " + Integer.toBinaryString(x2));
24+
System.out.println("XOR: " + Integer.toBinaryString(xor(x1, x2)));
25+
}
26+
27+
private static int xor(int x, int y) {
28+
return (x | y) - (x & y);
29+
}
30+
}

0 commit comments

Comments
 (0)