Torna alle sfide
Facile 0 risolte 0% di accettazione

Absolute Value Without abs

Compute an absolute value with a condition.

Cosa imparerai

  • Flip the sign of negative numbers
  • Write a function without built-ins
  • Handle zero correctly

Problema

Mostra traduzione

The absolute value of a number is its distance from zero. Compute it with an if statement instead of a built-in abs function.

Implement absolute_value(n).

Input

n: Any integer.

Output

Return n if it is zero or positive, otherwise -n.

Vincoli

-1,000,000,000 ≤ n ≤ 1,000,000,000

Esempi

Esempio 1
Input:
n = -42

Output atteso:
expected = 42
Input:
long long n = -42;

Output atteso:
long long expected = 42;
Input:
long n = -42;

Output atteso:
long expected = 42;

Spiegazione

-42 is negative, so the answer is 42.

Esempio 2
Input:
n = 15

Output atteso:
expected = 15
Input:
long long n = 15;

Output atteso:
long long expected = 15;
Input:
long n = 15;

Output atteso:
long expected = 15;

Spiegazione

15 is already positive, so it stays 15.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A number is unchanged if it is already nonnegative.

Suggerimento 2

Only negative values need to be flipped to their opposite.

Suggerimento 3

Zero should stay zero, so treat it with the nonnegative case.

Complessità attesa

O(1) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.