Fast way to multiply a number by 7
EasyUpdated: Sep 20, 2025
Problem
Given an integer x, compute 7 * x efficiently using bitwise operations and additions/shifts.
Examples
Example 1
Input: x = 5
Output: 35
Example 2
Input: x = -3
Output: -21
Solution
Multiplying by small constants is often faster when expressed as shifts and adds. We show two compact methods: shift-and-subtract (recommended) and shift-and-add.
Method 1 — Shift and subtract (recommended)
Intuition
Observe that 7 = 8 - 1, and 8 * x is x << 3. So 7*x = (x << 3) - x. This uses a single left shift and one subtraction.
Approach
- Compute
t = x << 3(equivalent tox * 8). - Return
t - x. - Use types that avoid overflow for large inputs if needed.
Code
C++
class Solution {
public:
long multiply_by_7(long x) {
long t = x << 3; // x * 8
return t - x; // 8x - x = 7x
}
};
Go
package main
func MultiplyBy7(x int64) int64 {
t := x << 3 // x * 8
return t - x
}
Java
class Solution {
public long multiplyBy7(long x) {
long t = x << 3; // x * 8
return t - x; // 7 * x
}
}
Python
class Solution:
def multiply_by_7(self, x: int) -> int:
t = x << 3 # x * 8
return t - x
Complexity
- ⏰ Time complexity:
O(1)— constant number of bit/arith operations. - 🧺 Space complexity:
O(1).
Method 2 — Shift and add (alternative)
Intuition
Use 7 = 4 + 2 + 1, so 7*x = (x<<2) + (x<<1) + x — three shifts and two additions.
Approach
- Compute
a = x << 2(4x),b = x << 1(2x), then returna + b + x.
Code
C++
class Solution {
public:
long multiply_by_7_alt(long x) {
return (x << 2) + (x << 1) + x; // 4x + 2x + x
}
};
Go
func MultiplyBy7Alt(x int64) int64 {
return (x << 2) + (x << 1) + x
}
Java
class Solution {
public long multiplyBy7Alt(long x) {
return (x << 2) + (x << 1) + x;
}
}
Python
class Solution:
def multiply_by_7_alt(self, x: int) -> int:
return (x << 2) + (x << 1) + x
Complexity
- ⏰ Time complexity:
O(1). - 🧺 Space complexity:
O(1).