File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments