Refactor BinaryToDecimal class (#4135)

This commit is contained in:
Sukruti Mallesh 2023-04-03 07:42:50 -07:00 committed by GitHub
parent d160156003
commit 8798e042a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 5 deletions

View File

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

View File

@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
public class BinaryToDecimalTest {
@Test
// Test converting binary to decimal
public void testBinaryToDecimal() {
// zeros at the starting should be removed
assertEquals(0, BinaryToDecimal.binaryToDecimal(0));
@ -15,4 +16,18 @@ public class BinaryToDecimalTest {
assertEquals(63, BinaryToDecimal.binaryToDecimal(111111));
assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000));
}
@Test
// Test converting negative binary numbers
public void testNegativeBinaryToDecimal() {
assertEquals(-1, BinaryToDecimal.binaryToDecimal(-1));
assertEquals(-42, BinaryToDecimal.binaryToDecimal(-101010));
}
@Test
// Test converting binary numbers with large values
public void testLargeBinaryToDecimal() {
assertEquals(262144L, BinaryToDecimal.binaryToDecimal(1000000000000000000L));
assertEquals(524287L, BinaryToDecimal.binaryToDecimal(1111111111111111111L));
}
}