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+ import java .util .Scanner ;
2+
3+ /*
4+ Given a number 'n' check if the number is odd or even using bit manipulation.
5+ Idea: If a number is even then its LSB must be unset and if the number is odd its LSB must be set.
6+ We can use bitwise AND with 1 to check this condition.
7+ */
8+ public class CheckOddEven {
9+ public static void main (String [] args ) {
10+ Scanner sc = new Scanner (System .in );
11+
12+ int n = sc .nextInt ();
13+
14+ if (isEven (n )) {
15+ System .out .println (n + " is even" );
16+ } else {
17+ System .out .println (n + " is odd" );
18+ }
19+ }
20+
21+ static boolean isEven (int n ) {
22+ //If n is even then LSB must be unset(0) therefore bitwise AND with 1 must be 0 as (0 & 1) == 0
23+ //If If n is odd then LSB must be set(1) therefore bitwise AND with 1 must be 1 as (1 & 1) == 1
24+ return (n & 1 ) == 0 ;
25+ }
26+ }
You can’t perform that action at this time.
0 commit comments