forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapNibbles.java
More file actions
31 lines (26 loc) · 810 Bytes
/
SwapNibbles.java
File metadata and controls
31 lines (26 loc) · 810 Bytes
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
import java.util.Scanner;
public class SwapNibbles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int num = sc.nextInt();
int result = swapNibbles(num);
System.out.println("Number after swapping nibbles:" + result);
sc.close();
}
private static int swapNibbles(int x) {
/* (x & 0x0F) << 4 gives us the last 4 bits of the number and
shifts it by 4 bits to the left.
(x & 0xF0) >> 4 gives us the last 4 bits of the number and
shifts it to right by 4 bits. */
return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
}
}
/*
* Sample input/output
* Enter a number:
* 100
* Number after swapping nibbles:70
*
* Space and Time complexity = O(1)
*/