Easy 0 solved 0% acceptance

Square a Number

Multiply an integer by itself.

What you'll learn

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

Problem

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.

Constraints

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

Examples

Example 1
Input:
n = 12

Expected output:
expected = 144
Input:
long long n = 12;

Expected output:
long long expected = 144;
Input:
long n = 12;

Expected output:
long expected = 144;

Explanation

12 × 12 = 144.

Example 2
Input:
n = -7

Expected output:
expected = 49
Input:
long long n = -7;

Expected output:
long long expected = 49;
Input:
long n = -7;

Expected output:
long expected = 49;

Explanation

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

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

A number times itself always gives a nonnegative result.

Hint 3

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

Expected complexity

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

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.