Problem overview
The method parity takes a non-negative integer n and returns the string "even" if n is divisible by 2, and "odd" otherwise. For n = 12 the answer is "even", because 12 divided by 2 leaves nothing over.
Approach
An even number leaves remainder 0 when divided by 2, and an odd number leaves remainder 1. The modulo operator % gives the remainder, so 12 % 2 is 0 and 13 % 2 is 1. The test n % 2 == 0 is therefore the whole problem.
Zero is even: 0 % 2 is 0. The method needs no special case for it.
Step by step
- Write an
ifthat checks for evenness. The condition isn % 2 == 0. Leave the body empty for now. - Return
"even"inside theif. Returning ends the method right there. - Return
"odd"after theif. This line is reached only whennis not even, because an evennhas already returned. Noelseis needed.
The solution in Scala
class Solution {
def parity(n: Int): String = {
if (n % 2 == 0) {
return "even"
}
return "odd"
}
}
The Scala details:
- Two different operators.
%computes the remainder and==compares. The expressionn % 2 == 0reads as "the remainder of n divided by 2 equals 0". The%is evaluated first. - The result type is declared.
: Stringafter the parameter list says what the method returns. Methods that usereturnmust have one. - Early return replaces
else. The same method can be written asif (n % 2 == 0) "even" else "odd", with noreturnat all, since anif-elseis an expression. Both versions return the same results for every input.
Using the method
To try it, create a Solution and call the method: new Solution().parity(12) returns "even". The method does not print anything; it hands the string back to the caller, who decides what to do with it, such as passing it to println.
Why the remainder works
Every integer is either twice some whole number or one more than twice a whole number. In the first case, dividing by 2 leaves nothing over, and in the second it leaves 1. Those are the only two possible remainders, which is why a single comparison with 0 splits all integers into two groups with nothing left out. Counting 12, 13 and 14 shows the pattern: the remainders are 0, 1, 0, and they keep alternating as the number grows.
Complexity
The method does one remainder operation and one comparison. Time and extra space are both constant, however large n is.
Edge cases and common mistakes
- Zero.
parity(0)is"even". - The smallest odd number.
parity(1)is"odd", because1 % 2is 1. - Testing for odd with
== 1. It works for non-negative numbers, which is all this lesson uses. For negative numbers, the remainder takes the sign of the dividend, so-3 % 2is-1. Comparing with 0 is the safe check. - Using
=instead of==. A single=assigns and doesn't compile as a condition. - Dividing instead of taking the remainder.
n / 2is integer division and gives a quotient, not a remainder. - Wrong text. The strings are lowercase:
"even"and"odd".
Testing
parity(12)gives"even".parity(13)gives"odd".parity(0)gives"even".parity(1)gives"odd".
