Problem#
Given an integer x
, compute 7 * x
efficiently using bitwise operations and additions/shifts.
Examples#
Example 1#
1
2
Input: x = 5
Output: 35
Example 2#
1
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 to x * 8
).
Return t - x
.
Use types that avoid overflow for large inputs if needed.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
class Solution {
public :
long multiply_by_7(long x) {
long t = x << 3 ; // x * 8
return t - x; // 8x - x = 7x
}
};
1
2
3
4
5
6
package main
func MultiplyBy7 (x int64 ) int64 {
t := x << 3 // x * 8
return t - x
}
1
2
3
4
5
6
class Solution {
public long multiplyBy7 (long x) {
long t = x << 3; // x * 8
return t - x; // 7 * x
}
}
1
2
3
4
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 return a + b + x
.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
class Solution {
public :
long multiply_by_7_alt(long x) {
return (x << 2 ) + (x << 1 ) + x; // 4x + 2x + x
}
};
1
2
3
func MultiplyBy7Alt (x int64 ) int64 {
return (x << 2 ) + (x << 1 ) + x
}
1
2
3
4
5
class Solution {
public long multiplyBy7Alt (long x) {
return (x << 2) + (x << 1) + x;
}
}
1
2
3
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)
.