Problem overview
The method negative takes an integer n and returns its negative. A negative input comes back unchanged. For example, negative(4) is -4, negative(15) is -15, negative(-4) is -4 and negative(0) is 0.
In short, the result is never positive: whatever sign the input has, the output is zero or below.
Approach
Two cases need different treatment. If n is already below zero, return it as it is. If it is zero or above, flip its sign with the unary minus, -n. Zero is covered by the second case, and -0 is just 0.
It might be tempting to negate always, but that would turn -4 into 4. The if keeps negative values out of the negation.
Step by step
- Write the
if. The condition isn < 0, which means the input is already negative. - Return
ninside the block. No change is needed. - Add an
elsethat returns-n. For zero or a positive input, the unary minus gives the negative value.
The solution in Scala
class Solution {
def negative(n: Int): Int = {
if (n < 0) {
return n
} else {
return -n
}
}
}
Details worth knowing about this Scala code:
- The return type is required with
return. A method that uses thereturnkeyword must declare its result type, here: Int. The compiler won't infer it. - The unary minus.
-nnegates anInt. It is a method on the number, but it reads like the sign in arithmetic. - Every path must produce an
Int. If you delete theelsebranch and keep onlyif (n < 0) { return n }, the compiler reports a type mismatch: foundUnit, requiredInt, with a hint that anelsepart may be missing. The method would have no value to give back whennis not negative. returnis optional in Scala. The last expression of a block is its value, soif (n < 0) n else -nis the same method written more briefly. The lesson uses explicitreturnto make the two exits clear.
Complexity
The method makes one comparison and at most one negation, so it takes constant time and constant extra space.
A walk through the cases
For n = 15: 15 < 0 is false, so the else branch runs and returns -15. For n = -4: -4 < 0 is true, so the if branch returns -4 and the method ends. The else block is never reached. For n = 0: 0 < 0 is false, so the result is -0, and integers have no negative zero, so it is simply 0.
Edge cases and common mistakes
- Zero.
0 < 0is false, so theelsebranch returns-0, which is0. The result is right. - Negative input. Always negating gives
4for-4. The condition prevents that. - Using
n <= 0. It still works for zero, since returningnand returning-ngive the same result there. The lesson'sn < 0says exactly what the task describes. - Dropping the return type.
def negative(n: Int) = { ... return ... }doesn't compile, becausereturnneeds an explicit result type. - Extreme values.
Int.MaxValuebecomes-2147483647without trouble. The onlyIntwhose negation overflows isInt.MinValue, and that value is negative, so it is returned before any negation happens.
Testing
negative(4)gives-4.negative(15)gives-15.negative(-4)gives-4.negative(0)gives0.
