Problem overview
The method printEvenOdd(_ n: Int) receives a positive integer n. For every number from 0 to n - 1 it prints one line: the word odd if the number is odd, or the number itself if it is even. The method returns nothing.
For n = 6 the numbers are 0, 1, 2, 3, 4 and 5, and the output is:
0
odd
2
odd
4
odd
Approach: loop, then choose between two outputs
Each number needs the same treatment: test whether it is odd, and print one of two things. That is a loop that visits the numbers 0 to n - 1, with an if and an else inside it. The test uses the remainder operator: a number divided by 2 leaves remainder 1 when it is odd and 0 when it is even.
Step by step
- Loop with a half-open range.
for i in 0..<nvisits 0, 1, ...,n - 1. The endnis left out, which is exactly the range the task asks for. - Test for odd. Inside the loop, an
ifchecksi % 2 == 1. If it is true, print the string"odd". - Handle the rest with
else. A number that is not odd is even, so theelsebranch printsi. Exactly one of the two branches runs on every pass.
A short trace
For n = 3 the loop runs with i equal to 0, 1 and 2. At 0 the remainder is 0, so the test fails and the else branch prints 0. At 1 the remainder is 1, so the method prints odd. At 2 the remainder is 0 again and it prints 2. The range ends before 3, so the loop stops.
The solution in Swift
class Solution {
func printEvenOdd(_ n: Int) {
for i in 0..<n {
if i % 2 == 1 {
print("odd")
} else {
print(i)
}
}
}
}
Swift details worth knowing:
0..<nversus0...n. The closed range would also print a line fornitself, one line too many.- Two kinds of output.
print("odd")prints a string andprint(i)prints anInt. Both calls are fine, becauseprintaccepts any value, and both end the line. - Testing for 1. Because the loop only sees non-negative numbers, the remainder is 0 or 1. With negative numbers,
-3 % 2would be -1 in Swift, so a test for== 1would miss negative odd numbers. Here that cannot happen. - The loop variable
iis a constant created by the loop, and it is visible only inside it. - When
nis 0. The range0..<0is empty and valid, so nothing is printed. A negativenwould crash, as the range would have its end below its start, but the task guarantees a positiven.
Complexity
Time: O(n). The loop runs n times and each pass does constant work.
Space: O(1). No data structure grows with n.
Edge cases and common mistakes
n = 1. Only 0 is visited, so the output is a single line,0.- Printing the quotes.
print("odd")printsoddwithout the quotation marks, which is what is wanted. - Forgetting the else. Without it, even numbers would print nothing, since the only
printis inside theif. - Using
=for comparison.i % 2 = 1is a compile error. Use==. - Starting at 1. A loop from 1 would skip 0 and print a wrong first line.
Testing
printEvenOdd(6)prints 0, odd, 2, odd, 4, odd.printEvenOdd(1)prints 0.printEvenOdd(3)prints 0, odd, 2.
