Skip to content
ExamSpine

Lesson 4.3 · Write it

Absolute value

A functionPython or Java6 tests, 3 of them hidden

On a phone? Put the lines in order instead

Write a function that returns the absolute value of a whole number (its distance from zero, always zero or positive).

  1. n is a whole number from -1000 to 1000: it can be negative, zero, or positive.
  2. If n is negative, return its positive version.
  3. If n is zero or positive, return it unchanged.
  4. Do not use any built-in absolute-value function.

Only the number your function returns is checked.

def absolute_value(n: int) -> int

You cannot use these in this question:

  • abs()

This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • absolute_value(-5) should return 5: a negative number becomes positive (rule 2)
  • absolute_value(3) should return 3: a positive number stays the same (rule 3)
  • absolute_value(0) should return 0: zero stays zero (rule 3)

public static int absoluteValue(int n)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Math.abs()

This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • absoluteValue(-5) should return 5: a negative number becomes positive (rule 2)
  • absoluteValue(3) should return 3: a positive number stays the same (rule 3)
  • absoluteValue(0) should return 0: zero stays zero (rule 3)
solution.pySolution.java