-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Longs.java
48 lines (43 loc) · 1.82 KB
/
Longs.java
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
package com.jwetherell.algorithms.numbers;
import java.math.BigDecimal;
public class Longs {
public static final String toBinaryUsingDivideAndModulus(long numberToConvert) {
long longNumber = numberToConvert;
if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
StringBuilder builder = new StringBuilder();
long temp = 0l;
while (longNumber > 0) {
temp = longNumber;
longNumber = temp / 2;
builder.append(temp % 2);
}
return builder.reverse().toString();
}
public static final String toBinaryUsingShiftsAndModulus(long numberToConvert) {
long longNumber = numberToConvert;
if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
StringBuilder builder = new StringBuilder();
long temp = 0l;
while (longNumber > 0) {
temp = longNumber;
longNumber = (temp >> 1);
builder.append(temp % 2);
}
return builder.reverse().toString();
}
public static final String toBinaryUsingBigDecimal(long numberToConvert) {
long longNumber = numberToConvert;
if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
StringBuilder builder = new StringBuilder();
BigDecimal zero = new BigDecimal(0);
BigDecimal two = new BigDecimal(2);
BigDecimal number = new BigDecimal(longNumber);
BigDecimal[] decimals = null;
while (number.compareTo(zero) > 0) {
decimals = number.divideAndRemainder(two);
number = decimals[0];
builder.append(decimals[1]);
}
return builder.reverse().toString();
}
}