Skip to content

Commit 23949ca

Browse files
authored
Add test case for BinaryToDecimal (TheAlgorithms#3684)
1 parent 2c9edc9 commit 23949ca

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java

+12-9
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,26 @@
77
*/
88
class BinaryToDecimal {
99

10+
public static int binaryToDecimal(int binNum) {
11+
int binCopy, d, s = 0, power = 0;
12+
binCopy = binNum;
13+
while (binCopy != 0) {
14+
d = binCopy % 10;
15+
s += d * (int) Math.pow(2, power++);
16+
binCopy /= 10;
17+
}
18+
return s;
19+
}
20+
1021
/**
1122
* Main Method
1223
*
1324
* @param args Command line arguments
1425
*/
1526
public static void main(String args[]) {
1627
Scanner sc = new Scanner(System.in);
17-
int binNum, binCopy, d, s = 0, power = 0;
1828
System.out.print("Binary number: ");
19-
binNum = sc.nextInt();
20-
binCopy = binNum;
21-
while (binCopy != 0) {
22-
d = binCopy % 10;
23-
s += d * (int) Math.pow(2, power++);
24-
binCopy /= 10;
25-
}
26-
System.out.println("Decimal equivalent:" + s);
29+
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextInt()));
2730
sc.close();
2831
}
2932
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.thealgorithms.conversions;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
public class BinaryToDecimalTest {
8+
9+
@Test
10+
public void testBinaryToDecimal() {
11+
//zeros at the starting should be removed
12+
assertEquals(0, BinaryToDecimal.binaryToDecimal(0));
13+
assertEquals(1, BinaryToDecimal.binaryToDecimal(1));
14+
assertEquals(5, BinaryToDecimal.binaryToDecimal(101));
15+
assertEquals(63, BinaryToDecimal.binaryToDecimal(111111));
16+
assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000));
17+
}
18+
}

0 commit comments

Comments
 (0)