Start learning free

LESSON 83 OF 348 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating abs() in Kotlin: Absolute Value with if and else

Practice Read the full explanation

The abs() function returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function abs() that recreates this functionality.

Examples:

abs(-1.217197940) ➞ 1.21719794

abs(-544.0) ➞ 544

abs(250.3) ➞ 250.3

abs(0) ➞ 0

abs(-0.14) ➞ 0.14

Note:

Do not use the abs() function provided by Kotlin (it will defeat the purpose of the challenge)


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 - CHALLENGES

    Recreating Abs in Kotlin, explained

    Problem overview

    The absolute value of a number is its distance from zero, which means its positive version. The absolute value of -5 is 5, the absolute value of 5 is 5, and the absolute value of 0 is 0. The task is to write your own abs function without using the one Kotlin provides, because the point is to practise a simple decision.

    In this lesson, the function is a member of class Solution and has the signature fun abs(n: Int): Int. It takes an Int and returns an Int, so it works with whole numbers. Examples: abs(-5) returns 5, abs(250) returns 250 and abs(0) returns 0.

    Approach

    Think about what the function has to do for each kind of input:

    • A negative number must change sign.
    • Zero and positive numbers are already correct, so they are returned as they are.

    That is a two-way choice, which is exactly what if and else are for. The only value to test is whether n is below zero.

    Step by step

    1. Test for a negative number. Write an if statement with the condition n < 0. Only negative inputs need to change, so only they enter the block.
    2. Negate inside the if. return -n flips the sign. Negating a negative number gives a positive one: -(-5) is 5.
    3. Return the input in the else. Write } else { on one line after the if body, and return n unchanged. Zero lands here too, which is correct, because the absolute value of 0 is 0.

    The solution in Kotlin

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

    A few Kotlin details are worth knowing:

    • A function must return on every path. A function with the return type Int must return an Int whatever the input. Here the if and the else each end in a return, so the compiler is satisfied.
    • The unary minus. -n means "the negative of n". It is an operator applied to one value, not a subtraction.
    • if is also an expression. The same logic fits on one line: fun abs(n: Int): Int = if (n < 0) -n else n. The block form above is clearer while you are learning.
    • The name abs. Kotlin has its own abs in kotlin.math, but it needs an import. Because the function here is a member of the class and its name is abs, a call such as abs(-5) inside the class uses your version.

    Tracing two calls

    For abs(-5), the condition -5 < 0 is true, so the function returns -(-5), which is 5. For abs(7), the condition 7 < 0 is false, so the else block runs and the function returns 7. Exactly one of the two return lines runs on every call, and the other is skipped.

    Edge cases and common mistakes

    • Zero. abs(0) returns 0 through the else branch. Using n <= 0 would also work, since -0 is 0.
    • Returning n in both branches. Copying the line by mistake leaves negative numbers unchanged.
    • Writing return n = -n or n = -n. A function parameter in Kotlin is read-only, so you cannot assign to it. Return the new value instead.
    • The smallest Int. An Int has 32 bits, ranging from -2147483648 to 2147483647. The value 2147483648 does not fit, so abs(Int.MIN_VALUE) returns -2147483648 in this function, because -n wraps around silently. Kotlin's own absolute value function behaves the same way for that one input.
    • Fractional numbers. This function takes an Int, so it can't be called with -1.5. To handle decimals, the parameter and the return type would be Double.

    Testing

    • abs(-5) returns 5.
    • abs(250) returns 250.
    • abs(0) returns 0.
    • abs(-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