Problem overview
The method negative takes an integer n and returns the negative of that number. A number that is already negative comes back unchanged.
negative(4) gives -4
negative(15) gives -15
negative(-4) gives -4
negative(0) gives 0
This differs from the previous exercise because the method returns a number instead of printing a word. The caller gets a value it can use in further calculations.
Approach
There are two cases. If n is below zero, it already has the right sign, so return it as it is. Otherwise n is zero or positive, and putting a minus sign in front of it gives the value we want. The unary minus -n flips the sign of a positive number, and -0 is still 0, so zero needs no special case.
A tempting shortcut is to always return -n. It works for 4 and 15, but for -4 it returns 4, which is the wrong sign. The condition is what stops the method from turning negative numbers positive.
Step by step
- Write the
if. The condition isn < 0, which means the input is already negative. - Return
ninside it. Thereturnstatement hands the value back and ends the method on the spot. - Add the
elsebranch and return-n. It runs for zero and for positive inputs, where the unary minus produces the negative value.
The solution in Swift
class Solution {
func negative(_ n: Int) -> Int {
if n < 0 {
return n
} else {
return -n
}
}
}
Swift details worth knowing:
- The return type.
-> Intpromises that the method gives back anInt. Every possible path through the method must then end in areturn. Here both branches do, so the compiler is satisfied. - A missing return is an error. If you write only the
ifbranch, the compiler stops withmissing return in instance method expected to return 'Int', because a non-negativenwould reach the end without returning anything. That is why the starter code, with an empty body, doesn't compile until the method returns something on every path. - Unary minus.
-nis an expression that produces a new value. It doesn't changen, which is a constant inside the method, as all parameters are in Swift. - Calling it. After
let s = Solution(), the calls.negative(15)returns-15, andprint(s.negative(-4))prints-4. - The underscore in
_ n: Intmeans callers writenegative(15)without a label.
Edge cases and common mistakes
- Zero.
negative(0)goes to theelsebranch and returns-0, which is the integer0. Integers have no negative zero in Swift. - Printing instead of returning.
print(-n)shows a number on the console but gives the caller nothing. The tests check the returned value. - Using
n <= 0. The result stays correct, because both branches give 0 for zero, but the strict comparison states the intent better. - Returning
abs(n)or flipping the wrong case. The absolute value is the opposite of what the task asks. - Largest values.
negative(Int.max)returns-9223372036854775807, which fits in anInt.
Testing
negative(4)returns-4.negative(15)returns-15.negative(-4)returns-4.negative(0)returns0.
