File tree 2 files changed +28
-23
lines changed
main/java/com/thealgorithms/conversions
test/java/com/thealgorithms/conversions
2 files changed +28
-23
lines changed Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .conversions ;
2
2
3
- import java .util .Scanner ;
4
-
5
3
/**
6
4
* This class converts a Binary number to a Decimal number
7
5
*/
8
6
final class BinaryToDecimal {
9
- private BinaryToDecimal () {
10
- }
7
+ private static final int BINARY_BASE = 2 ;
11
8
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 () {
24
10
}
25
11
26
12
/**
27
- * Main Method
13
+ * Converts a binary number to its decimal equivalent.
28
14
*
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.
30
18
*/
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 ;
36
32
}
37
33
}
Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .conversions ;
2
2
3
3
import static org .junit .jupiter .api .Assertions .assertEquals ;
4
+ import static org .junit .jupiter .api .Assertions .assertThrows ;
4
5
5
6
import org .junit .jupiter .api .Test ;
7
+ import org .junit .jupiter .params .ParameterizedTest ;
8
+ import org .junit .jupiter .params .provider .CsvSource ;
6
9
7
10
public class BinaryToDecimalTest {
8
11
@@ -30,4 +33,10 @@ public void testLargeBinaryToDecimal() {
30
33
assertEquals (262144L , BinaryToDecimal .binaryToDecimal (1000000000000000000L ));
31
34
assertEquals (524287L , BinaryToDecimal .binaryToDecimal (1111111111111111111L ));
32
35
}
36
+
37
+ @ ParameterizedTest
38
+ @ CsvSource ({"2" , "1234" , "11112" , "101021" })
39
+ void testNotCorrectBinaryInput (long binaryNumber ) {
40
+ assertThrows (IllegalArgumentException .class , () -> BinaryToDecimal .binaryToDecimal (binaryNumber ));
41
+ }
33
42
}
You can’t perform that action at this time.
0 commit comments