- Code snippets for Integer to binary string conversion
This commit is contained in:
vatsalgosar 2020-07-01 01:41:39 +05:30 committed by GitHub
parent 1ff6672223
commit eff6ed12e6
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.baeldung.integerToBinary;
public class IntegerToBinary {
public static String convertIntegerToBinary(int n) {
if(n == 0) {
return "0";
}
StringBuilder binaryNumber = new StringBuilder();
while (n > 0) {
int remainder = n % 2;
binaryNumber.append(remainder);
n /= 2;
}
binaryNumber = binaryNumber.reverse();
return binaryNumber.toString();
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.integerToBinary;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IntegerToBinaryUnitTest {
@Test
public void givenAnInteger_whenConvertToBinary_thenGetBinaryString() {
int n = 7;
String binaryString = IntegerToBinary.convertIntegerToBinary(n);
assertEquals("111", binaryString);
}
@Test
public void givenAnInteger_whenToBinaryStringCalled_thenGetBinaryString() {
int n = 7;
String binaryString = Integer.toBinaryString(n);
assertEquals("111", binaryString);
}
@Test
public void givenAnInteger_whenToStringCalled_thenGetBinaryString() {
int n = 7;
String binaryString = Integer.toString(n, 2);
assertEquals("111", binaryString);
}
}