Skip to content

Commit 83ff911

Browse files
Merge pull request #217 from AayushBangroo/master
CheckOddEven using BitManip code added
2 parents a9b9f5f + c2895a5 commit 83ff911

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Bit Manipulation/CheckOddEven.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)