Problem#
Decide whether an integer is even or odd.
- Input: an integer
n
(can be negative, zero, or positive).
- Output: a boolean or small integer indicating parity (e.g.,
true
/false
or 0
/1
for even/odd
) or the words even
/odd
depending on API.
Examples#
Example 1#
1
2
|
Input: n = 3
Output: odd
|
Example 2#
1
2
|
Input: n = 10
Output: even
|
Similar Problems
Solution#
Method 1 — Modulo operator#
Intuition#
An integer n
is even iff n % 2 == 0
. This directly uses the definition of even/odd.
Approach#
- Compute
r = n % 2
.
- If
r == 0
, return even
; otherwise return odd
.
Code#
1
2
3
4
|
class Solution {
public:
static bool is_even(long long n) { return (n % 2) == 0; }
};
|
1
2
3
|
package main
func IsEven(n int64) bool { return n%2 == 0 }
|
1
2
3
|
class Solution {
public static boolean isEven(long n) { return n % 2 == 0; }
}
|
1
|
object Solution { fun isEven(n: Long) = n % 2L == 0L }
|
1
2
3
4
5
6
|
class Solution:
def is_even(self, n: int) -> bool:
return n % 2 == 0
def print_parity(self, n: int) -> str:
return 'even' if self.is_even(n) else 'odd'
|
1
2
3
4
|
pub struct Solution;
impl Solution {
pub fn is_even(n: i128) -> bool { n % 2 == 0 }
}
|
Complexity#
- ⏰ Time complexity:
O(1)
— single arithmetic operation.
- 🧺 Space complexity:
O(1)
.
Method 2 — Bitwise LSB Test (n & 1
)#
Intuition#
The binary LSB (b0
) contributes 1
when set. x & 1
preserves only b0
. If (x & 1) == 0
then b0
is 0
and x
is even; otherwise x
is odd.
Approach#
- Compute
b = n & 1
.
- If
b == 0
number is even, else odd.
Edge cases#
- Negative numbers: two’s complement representation preserves parity, so the same test works for negatives.
- Very large integers (language-dependent): ensure bitwise operations are valid for the integer width used.
Code#
1
2
3
4
|
class SolutionBit {
public:
static bool is_even(long long n) { return (n & 1LL) == 0LL; }
};
|
1
2
3
|
package main
func IsEvenBit(n int64) bool { return (n & 1) == 0 }
|
1
2
3
|
class Solution {
public static boolean isEvenBit(long n) { return (n & 1L) == 0L; }
}
|
1
2
3
|
class Solution:
def is_even_bit(self, n: int) -> bool:
return (n & 1) == 0
|
1
2
3
4
|
pub struct Solution;
impl Solution {
pub fn is_even_bit(n: i128) -> bool { (n & 1) == 0 }
}
|
Complexity#
- ⏰ Time complexity:
O(1)
— single bitwise operation.
- 🧺 Space complexity:
O(1)
.