Skip to content

Commit ca3f25c

Browse files
committed
IsNthBitSet code added
1 parent 36822a0 commit ca3f25c

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Bit Manipulation/IsNthBitSet.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Problem Statement: Given two numbers 'a' and 'n', check if nth bit is set in 'a'. Consider 0 based indexing.
3+
Idea: Do a bitwise AND operation with 1 at the nth position. If the result is non-zero bit is set otherwise
4+
it is unset.
5+
6+
Examples:
7+
8+
Input: 4 2
9+
Output: Bit is unset at position 2
10+
11+
Input: 10 4
12+
Output: Bit is set at position 4
13+
*/
14+
15+
import java.util.Scanner;
16+
17+
public class IsNthBitSet {
18+
public static void main(String[] args) {
19+
Scanner sc = new Scanner(System.in);
20+
21+
int a = sc.nextInt();
22+
int n = sc.nextInt();
23+
24+
checkNthBit(a, n);
25+
}
26+
27+
public static void checkNthBit(int a, int n) {
28+
if ((a & (1 << (n - 1))) != 0) {
29+
System.out.println("Bit is set at position " + n);
30+
} else {
31+
System.out.println("Bit is unset at position " + n);
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)