-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiplyUsingBits.java
More file actions
41 lines (33 loc) · 971 Bytes
/
Copy pathMultiplyUsingBits.java
File metadata and controls
41 lines (33 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
class MultiplyUsingBits {
static int add(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstNumber = sc.nextInt();
int secondNumber = sc.nextInt();
int result = 0;
int sign = 1;
if (secondNumber < 0) {
secondNumber = add(~secondNumber, 1);
sign = -1;
}
while (secondNumber != 0) {
if ((secondNumber & 1) == 1) {
result = add(result, firstNumber);
}
firstNumber = firstNumber << 1;
secondNumber = secondNumber >> 1;
}
if (sign == -1) {
result = add(~result, 1);
}
System.out.println(result);
}
}