Start learning free

LESSON 71 OF 348 · CONDITIONAL STATEMENTS

Return Negative in Kotlin: if, else and Unary Minus

Practice Read the full explanation

Create a function that takes a number as an argument and returns negative of that number. Return negative numbers without any change.

Examples:

negative(4) ➞ -4

negative(15) ➞ -15

negative(-4) ➞ -4

negative(0) ➞ 0

Hints:

You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    Return Negative in Kotlin, explained

    Problem overview

    The function negative(n: Int): Int must return the negative of the number it receives. A positive number flips its sign. A number that is already negative comes back unchanged. Zero stays zero. The examples show it:

    • negative(4) returns -4.
    • negative(15) returns -15.
    • negative(-4) returns -4, not 4.
    • negative(0) returns 0.

    Unlike the previous lessons in this chapter, this function doesn't print. It hands a value back to the caller, so the work happens in return statements.

    Approach

    The result is "never positive": for a positive input you negate, for a negative input you leave it alone. Negating blindly, with return -n for every input, would turn -4 into 4, which is wrong. So the function has to decide first, and the decision is the question "is n already below zero?". That is an if with an else.

    Zero needs no special handling. It is not less than zero, so it goes to the else branch, where -0 is still 0 for an integer.

    Step by step

    1. Test the sign. Write an if with the condition n < 0. When it is true, the input is already negative.
    2. Return it unchanged. Inside the if, return n. Nothing else needs to happen, and return ends the function on the spot.
    3. Negate everything else. In the else branch, return -n. The unary minus flips the sign of a positive number and leaves zero as zero.

    The solution in Kotlin

    class Solution {
        fun negative(n: Int): Int {
            if (n < 0) {
                return n
            } else {
                return -n
            }
        }
    }
    

    Kotlin details worth knowing:

    • The return type is declared. The : Int after the parameter list promises that every path through the function returns an Int.
    • Every path must return. The starter code has an empty body, and Kotlin rejects that with the error "missing return statement". The finished function returns in both branches, so the compiler is satisfied.
    • Unary minus. -n is an operator applied to one value. It doesn't change the variable n. It produces a new value, which is then returned. Parameters in Kotlin are read-only, so the function couldn't change n anyway.
    • Printing is not returning. Without a return, the caller gets nothing back, even if you println the right number.

    With the examples, negative(15) goes to the else branch and returns -15, and negative(-4) goes to the if branch and returns -4.

    Reading the two branches together

    Both branches return, so only one return ever runs for a given input. Once the first returns, the function is over and the second is never looked at. That is why the else is, strictly speaking, optional here: code placed after the if block can only be reached when the condition was false. Dropping the else gives a shorter shape, but writing it out is a clear way to start.

    Edge cases and common mistakes

    • Zero. With n < 0 it takes the else branch, where -n is 0 again, because integers have no negative zero. Using n <= 0 would also work here, because both branches give the same answer for zero.
    • Already negative input. Always returning -n flips -4 into 4. This is the mistake the third example is designed to catch.
    • Wrong direction in the test. Using n > 0 as the condition and returning n inside it gives the exact opposite of what is wanted.
    • The smallest Int. Int.MIN_VALUE, which is -2147483648, is negative, so the function returns it unchanged. That is the right result. The dangerous case would be negating it, since -Int.MIN_VALUE overflows and wraps back to itself, but the if sends it down the safe path.

    Testing

    Try these inputs and compare with the expected returns:

    • negative(4) returns -4.
    • negative(-4) returns -4.
    • negative(0) returns 0.
    • negative(1) returns -1.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free