Add test case for BinaryToDecimal (#3684)
This commit is contained in:
parent
2c9edc95b8
commit
23949cac47
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user