Given two integers a and b, compute the product a * b without using the multiplication operator (*). The allowed operations are bitwise shifts, bitwise logical operators, addition and subtraction. Preserve sign semantics for negative inputs and handle zero correctly.
Multiplication is repeated addition: a * b equals adding a to itself |b| times and adjusting sign at the end. This is the simplest approach when only + is available.
classSolution {
public:int multiply(int a, int b) {
bool neg = (a <0) ^ (b <0);
int abs_a = a <0?-a : a;
int abs_b = b <0?-b : b;
int ans =0;
for (int i =0; i < abs_b; ++i) ans += abs_a;
return neg ?-ans : ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
packagemainfuncmultiply(a, bint) int {
neg:= (a < 0) != (b < 0)
ifa < 0 { a = -a }
ifb < 0 { b = -b }
ans:=0fori:=0; i < b; i++ {
ans+=a }
ifneg { ans = -ans }
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmultiply(int a, int b) {
boolean neg = (a < 0) ^ (b < 0);
int absA = Math.abs(a);
int absB = Math.abs(b);
int ans = 0;
for (int i = 0; i < absB; ++i) ans += absA;
return neg ?-ans : ans;
}
}
1
2
3
4
5
6
7
8
classSolution:
defmultiply(self, a: int, b: int) -> int:
neg = (a <0) ^ (b <0)
a, b = abs(a), abs(b)
ans =0for _ in range(b):
ans += a
return-ans if neg else ans
Multiply by decomposing the multiplier into binary bits. Shift the multiplicand left when the multiplier’s current bit is considered and add it to the result when that bit is 1. Repeatedly halve the multiplier and double the multiplicand — this performs O(log |b|) additions.
classSolution {
public:int multiply(int a, int b) {
if (a ==0|| b ==0) return0;
bool neg = (a <0) ^ (b <0);
unsignedint ua = a <0?-static_cast<unsignedint>(a) : a;
unsignedint ub = b <0?-static_cast<unsignedint>(b) : b;
unsignedint ans =0;
while (ub) {
if (ub &1) ans += ua;
ua <<=1;
ub >>=1;
}
int res =static_cast<int>(ans);
return neg ?-res : res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
packagemainfuncmultiply(a, bint) int {
ifa==0||b==0 { return0 }
neg:= (a < 0) != (b < 0)
ifa < 0 { a = -a }
ifb < 0 { b = -b }
ans:=0forb!=0 {
ifb&1==1 { ans+=a }
a<<=1b>>=1 }
ifneg { ans = -ans }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintmultiply(int a, int b) {
if (a == 0 || b == 0) return 0;
boolean neg = (a < 0) ^ (b < 0);
int ua = Math.abs(a);
int ub = Math.abs(b);
int ans = 0;
while (ub != 0) {
if ((ub & 1) != 0) ans += ua;
ua <<= 1;
ub >>= 1;
}
return neg ?-ans : ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmultiply(self, a: int, b: int) -> int:
if a ==0or b ==0:
return0 neg = (a <0) ^ (b <0)
a, b = abs(a), abs(b)
ans =0while b:
if b &1:
ans += a
a <<=1 b >>=1return-ans if neg else ans