Skip to content

Commit e32cab3

Browse files
authored
refactor: BinaryToDecimal (#5330)
1 parent c20375a commit e32cab3

File tree

2 files changed

+28
-23
lines changed

2 files changed

+28
-23
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,33 @@
11
package com.thealgorithms.conversions;
22

3-
import java.util.Scanner;
4-
53
/**
64
* This class converts a Binary number to a Decimal number
75
*/
86
final class BinaryToDecimal {
9-
private BinaryToDecimal() {
10-
}
7+
private static final int BINARY_BASE = 2;
118

12-
public static long binaryToDecimal(long binNum) {
13-
long binCopy;
14-
long d;
15-
long s = 0;
16-
long power = 0;
17-
binCopy = binNum;
18-
while (binCopy != 0) {
19-
d = binCopy % 10;
20-
s += d * (long) Math.pow(2, power++);
21-
binCopy /= 10;
22-
}
23-
return s;
9+
private BinaryToDecimal() {
2410
}
2511

2612
/**
27-
* Main Method
13+
* Converts a binary number to its decimal equivalent.
2814
*
29-
* @param args Command line arguments
15+
* @param binaryNumber The binary number to convert.
16+
* @return The decimal equivalent of the binary number.
17+
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
3018
*/
31-
public static void main(String[] args) {
32-
Scanner sc = new Scanner(System.in);
33-
System.out.print("Binary number: ");
34-
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));
35-
sc.close();
19+
public static long binaryToDecimal(long binaryNumber) {
20+
long decimalValue = 0;
21+
long power = 0;
22+
23+
while (binaryNumber != 0) {
24+
long digit = binaryNumber % 10;
25+
if (digit > 1) {
26+
throw new IllegalArgumentException("Incorrect binary digit: " + digit);
27+
}
28+
decimalValue += (long) (digit * Math.pow(BINARY_BASE, power++));
29+
binaryNumber /= 10;
30+
}
31+
return decimalValue;
3632
}
3733
}

src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java

+9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package com.thealgorithms.conversions;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.CsvSource;
69

710
public class BinaryToDecimalTest {
811

@@ -30,4 +33,10 @@ public void testLargeBinaryToDecimal() {
3033
assertEquals(262144L, BinaryToDecimal.binaryToDecimal(1000000000000000000L));
3134
assertEquals(524287L, BinaryToDecimal.binaryToDecimal(1111111111111111111L));
3235
}
36+
37+
@ParameterizedTest
38+
@CsvSource({"2", "1234", "11112", "101021"})
39+
void testNotCorrectBinaryInput(long binaryNumber) {
40+
assertThrows(IllegalArgumentException.class, () -> BinaryToDecimal.binaryToDecimal(binaryNumber));
41+
}
3342
}

0 commit comments

Comments
 (0)