BAEL-4142 (#9622)
- Code snippets for Integer to binary string conversion
This commit is contained in:
parent
1ff6672223
commit
eff6ed12e6
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue