Skip to content

Add Test case for BinaryToDecimal #3684

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,26 @@
*/
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
*
* @param args Command line arguments
*/
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();
}
}
Original file line number Diff line number Diff line change
@@ -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));
}
}