Calculate square of a number without using *, / and pow()
Pattern: Bits basics
n × n is the sum of n shifted left by i, over every set bit i of n. Shifts and additions replace multiplication. A negative n has the same square as its absolute value.
The problem
Given a whole number n, return n² without using the * or / operators or a power function. For example, 5 gives 25,
-5 gives 25, and 0 gives 0. This guide keeps |n| ≤ 46340, so the answer fits in a 32-bit int.
The link above is a GeeksforGeeks article. The function name square and the size limit are this guide's own.
Think first
- Writing
nin binary as a sum of powers of two, what isn × n? - What does
n << iequal? - How do negative inputs change the answer?
Hints
Brute force, and why it fails
Add n to itself n times: O(n). Using the bits of n: O(log n) additions.
The key insight
Multiplication in base 2 is "shift and add": each set bit of one factor adds a shifted copy of the other.
Dry run
| result | 0 |
|---|
n = 5, which is 101 in binary. Its set bits are bit 0 and bit 2.
The plan
n = |n|; result = 0
for each bit i of n that is 1: result = result + (n << i)
return result
Complexity
- Time
O(log n)- Space
O(1)
One step per bit of n.
Edge cases
- 0 and 1: themselves.
- Negative inputs: the square is positive.
- The largest allowed, 46340: 2,147,395,600, just under the int limit.
I've built my logic, show the code
Java
class Solution {
public int square(int n) {
if (n < 0) n = -n; // (-n)^2 = n^2
int result = 0;
for (int bit = 0, m = n; m > 0; bit++, m >>= 1) {
if ((m & 1) == 1) result += n << bit; // n * n = sum of n * 2^bit over the set bits of n
}
return result;
}
}C++
class Solution {
public:
int square(int n) {
if (n < 0) n = -n; // (-n)^2 = n^2
int result = 0;
for (int bit = 0, m = n; m > 0; bit++, m >>= 1) {
if (m & 1) result += n << bit; // n * n = sum of n * 2^bit over the set bits of n
}
return result;
}
};Python
class Solution:
def square(self, n: int) -> int:
n = abs(n) # (-n)^2 = n^2
result, bit, m = 0, 0, n
while m > 0:
if m & 1:
result += n << bit # n * n = sum of n * 2^bit over the set bits of n
bit += 1
m >>= 1
return resultCommon mistakes
- Shifting the negative value without taking the absolute value first.
- Adding
1 << iinstead ofn << i. - Overflowing for inputs above 46340 in 32-bit types.