Skip to content

Commit f8d3b2a

Browse files
Merge pull request #113 from AayushBangroo/master
IsNthBitSet code added
2 parents d9934ba + 95b810e commit f8d3b2a

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Bit Manipulation/IsNthBitSet.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
//Create a mask that has only nth bit set
29+
int mask = 1 << (n - 1);
30+
31+
//If nth bit is set in 'a' then bitwise AND with mask
32+
//will give non-zero result
33+
if ((a & mask) != 0) {
34+
System.out.println("Bit is set at position " + n);
35+
}
36+
//If nth bit is unset in 'a' then bitwise AND with mask
37+
//will give zero result
38+
else {
39+
System.out.println("Bit is unset at position " + n);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)