-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMultiplyWithBitShifting.cs
57 lines (51 loc) · 1.39 KB
/
MultiplyWithBitShifting.cs
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
namespace PracticeQuestionsSharp.Exercises.Numbers
{
//Perform multiplication using only bit shift operations, addition and subtraction.
public static class MultiplyWithBitShifting
{
public static int Multiply(int a, int b)
{
if (a == 0 || b == 0) return 0;
int larger;
int smaller;
bool positive = true;
int sum = 0;
int place = 0;
if (a < 0 && b < 0)
{
//Result is positive, get absolute values to work with
a = Math.Abs(a);
b = Math.Abs(b);
}
else if (a < 0 || b < 0)
{
//If one side is negative, the result is negative
positive = false;
a = Math.Abs(a);
b = Math.Abs(b);
}
if (a < b)
{
larger = b;
smaller = a;
}
else
{
larger = a;
smaller = b;
}
while (smaller != 0)
{
if ((smaller & 1) == 1)
{
sum += larger << place;
}
smaller >>= 1;
place++;
}
return positive ? sum: -sum;
}
}
}