Check Whether a Floating-Point Number is Even or Odd
Problem
Given a floating-point number x provided as a string (e.g. "42.0", "17.5", "-8.000"), determine whether it represents an even integer, an odd integer, or is not an integer at all. Return "Even", "Odd" or "Not an integer".
The value is passed as a string because reading it into a double can lose precision for large magnitudes (e.g. "12345678901234567891.0"), and the point of the question is to reason about that.
Input / Output
- Input: a string representing a decimal number, optionally with a sign and a fractional part.
- Output: one of the three labels.
Examples
| Input | Output |
|---|---|
"42.0" | Even |
"17" | Odd |
"17.5" | Not an integer |
"-8.000" | Even |
"0.0" | Even |
"3.10" | Not an integer |
Constraints
1 <= |x| <= 100characters.- The string is a valid decimal literal.
Approach
- Strip a leading
+or-(parity does not depend on sign). - Split on the decimal point (if present) into
intPartandfracPart. - If
fracPartcontains any non-zero digit, the number is not an integer. - Otherwise the parity is decided by the last digit of
intPart: even if it is0, 2, 4, 6, 8, odd otherwise. Treat an emptyintPart(e.g.".0") as0.
Because only the last integer digit and the fractional digits are inspected, no numeric conversion is needed and the solution is exact for any length.
If you must work with an actual double. Use x == floor(x) (or modf) to check integrality, then fmod(x, 2) == 0 for evenness. Explain in the interview that for |x| >= 2^53 every double is an even integer (the spacing between representable values is at least 2), so the string approach is the only fully correct one.
Complexity
- Time: O(length of the string)
- Space: O(1)
Why interviewers like it
It looks trivial but exposes whether a candidate knows that floating-point numbers are not exact, that % is not defined on floats in some languages, and that parsing beats numeric tricks when precision matters.
Reference solution (Python)
def float_parity(x: str) -> str:
x = x.strip().lstrip('+-')
int_part, _, frac_part = x.partition('.')
if frac_part.strip('0'):
return "Not an integer"
last = int_part[-1] if int_part else '0'
return "Even" if last in "02468" else "Odd"
Test cases
| Input | Expected |
|---|---|
"42.0" | Even |
"17.5" | Not an integer |
"-8.000" | Even |
"12345678901234567891.0" | Odd |