Tutte le sfide
Facile 2 risolte 100.0% di accettazione

Square a Number

Multiply an integer by itself.

Cosa imparerai

  • Write a function that takes and returns a number
  • Multiply a value by itself
  • Handle negative inputs

Problema

Mostra traduzione

Return n multiplied by itself. The square of a negative number is positive.

Implement square_number(n).

Input

n: Any integer in the allowed range.

Output

Return n × n.

Vincoli

−3,000,000,000 ≤ n ≤ 3,000,000,000, so the square fits a signed 64-bit integer.

Esempi

Esempio 1
Input:
n = 12

Output atteso:
expected = 144
Input:
long long n = 12;

Output atteso:
long long expected = 144;
Input:
long n = 12;

Output atteso:
long expected = 144;

Spiegazione

12 × 12 = 144.

Esempio 2
Input:
n = -7

Output atteso:
expected = 49
Input:
long long n = -7;

Output atteso:
long long expected = 49;
Input:
long n = -7;

Output atteso:
long expected = 49;

Spiegazione

(−7) × (−7) = 49.

Come affrontarlo

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

Suggerimento 1

This is a direct multiplication problem, even for negative inputs.

Suggerimento 2

A number times itself always gives a nonnegative result.

Suggerimento 3

Watch for overflow in languages with fixed-size integers, though the result fits 64 bits here.

Complessità attesa

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

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 HJhettory Jurash Python 979 ms - 5/5 Vedi il codice
2 GTGarlic The Destroyer Rust 1,572 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 2 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le recensioni AI. Accedi e risolvi la sfida per partecipare alla discussione.