Add test case for BinaryToDecimal (#3684)

This commit is contained in:
Nandini Anagondi 2022-10-27 18:10:08 +05:30 committed by GitHub
parent 2c9edc95b8
commit 23949cac47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 9 deletions

View File

@ -7,6 +7,17 @@ import java.util.Scanner;
*/
class BinaryToDecimal {
public static int binaryToDecimal(int binNum) {
int binCopy, d, s = 0, power = 0;
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
s += d * (int) Math.pow(2, power++);
binCopy /= 10;
}
return s;
}
/**
* Main Method
*
@ -14,16 +25,8 @@ class BinaryToDecimal {
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int binNum, binCopy, d, s = 0, power = 0;
System.out.print("Binary number: ");
binNum = sc.nextInt();
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
s += d * (int) Math.pow(2, power++);
binCopy /= 10;
}
System.out.println("Decimal equivalent:" + s);
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextInt()));
sc.close();
}
}

View File

@ -0,0 +1,18 @@
package com.thealgorithms.conversions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BinaryToDecimalTest {
@Test
public void testBinaryToDecimal() {
//zeros at the starting should be removed
assertEquals(0, BinaryToDecimal.binaryToDecimal(0));
assertEquals(1, BinaryToDecimal.binaryToDecimal(1));
assertEquals(5, BinaryToDecimal.binaryToDecimal(101));
assertEquals(63, BinaryToDecimal.binaryToDecimal(111111));
assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000));
}
}