-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_odd_even.cpp
More file actions
58 lines (55 loc) · 3.93 KB
/
check_odd_even.cpp
File metadata and controls
58 lines (55 loc) · 3.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int num;
cin >> num;
if (num & 1) {
cout << "odd\n";
}
else {
cout << "even\n";
}
return 0;
}
/*
──────────────────────────────────────────────────────────────────────────────────────────
QUICK REFERENCE — Odd or Even Check Using Bitwise AND
──────────────────────────────────────────────────────────────────────────────────────────
Binary Representation (32-bit sample view)
──────────────────────────────────────────────────────────────────────────────────────────
1 = 0 0000000 00000000 00000000 00000001
2 = 0 0000000 00000000 00000000 00000010
↑ ↑
Sign Bit Least Significant Bit (LSB)
↑
Most Significant Bit (MSB)
──────────────────────────────────────────────────────────────────────────────────────────
Concept
──────────────────────────────────────────────────────────────────────────────────────────
• The **Least Significant Bit (LSB)** determines whether a number is odd or even.
If LSB = 1 → Number is **odd**
If LSB = 0 → Number is **even**
• Checking LSB can be done using bitwise AND:
→ Result = num & 1
→ If Result = 1 → odd
→ If Result = 0 → even
──────────────────────────────────────────────────────────────────────────────────────────
Example Run
──────────────────────────────────────────────────────────────────────────────────────────
Input:
13
Binary of 13 = 1101
↑
LSB = 1 → odd number
Output:
odd
──────────────────────────────────────────────────────────────────────────────────────────
Notes
──────────────────────────────────────────────────────────────────────────────────────────
• Bit positions start from **0** (rightmost bit).
• Works for both positive and negative integers.
• This check is faster than using modulo (%) since it directly inspects the LSB.
──────────────────────────────────────────────────────────────────────────────────────────
*/