Check if number is odd or even
EasyUpdated: Sep 19, 2025
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/falseor0/1foreven/odd) or the wordseven/odddepending on API.
Examples
Example 1
Input: n = 3
Output: odd
Example 2
Input: n = 10
Output: even
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, returneven; otherwise returnodd.
Code
C++
class Solution {
public:
static bool is_even(long long n) { return (n % 2) == 0; }
};
Go
package main
func IsEven(n int64) bool { return n%2 == 0 }
Java
class Solution {
public static boolean isEven(long n) { return n % 2 == 0; }
}
Kotlin
object Solution { fun isEven(n: Long) = n % 2L == 0L }
Python
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'
Rust
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 == 0number 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
C++
class SolutionBit {
public:
static bool is_even(long long n) { return (n & 1LL) == 0LL; }
};
Go
package main
func IsEvenBit(n int64) bool { return (n & 1) == 0 }
Java
class Solution {
public static boolean isEvenBit(long n) { return (n & 1L) == 0L; }
}
Python
class Solution:
def is_even_bit(self, n: int) -> bool:
return (n & 1) == 0
Rust
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).