Skip to content

Commit 5eafa52

Browse files
authored
Create BitManipulationAlgorithms
Algorithm 1: Find the Number Appearing Odd Times Algorithm 2: Swap Adjacent Bits of a Number Algorithm 3: Bitwise XOR of All Elements in an Array
1 parent 33dee07 commit 5eafa52

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

BitManipulationAlgorithms

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
public class BitManipulationAlgorithms {
6+
7+
// Algorithm 1: Find the Number Appearing Odd Times
8+
public static int findOdd(int[] arr) {
9+
int result = 0;
10+
for (int num : arr) {
11+
result ^= num;
12+
}
13+
return result;
14+
}
15+
16+
// Algorithm 2: Swap Adjacent Bits of a Number
17+
public static int swapBits(int n) {
18+
return ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
19+
}
20+
21+
// Algorithm 3: Bitwise XOR of All Elements in an Array
22+
public static int xorAll(int[] arr) {
23+
int result = 0;
24+
for (int num : arr) {
25+
result ^= num;
26+
}
27+
return result;
28+
}
29+
30+
public static void main(String[] args) {
31+
// Test Algorithm 1
32+
int[] arr1 = {1, 2, 3, 2, 3, 1, 3};
33+
System.out.println("Number appearing odd times: " + findOdd(arr1)); // Output: 3
34+
35+
// Test Algorithm 2
36+
int n = 23; // Binary: 10111
37+
System.out.println("Swapped adjacent bits: " + swapBits(n)); // Output: 43 (Binary: 101011)
38+
39+
// Test Algorithm 3
40+
int[] arr2 = {1, 2, 3, 4, 5};
41+
System.out.println("Bitwise XOR of all elements: " + xorAll(arr2)); // Output: 1
42+
}
43+
}

0 commit comments

Comments
 (0)