convert decimal to octal value

This commit is contained in:
Adan Rodriguez 2019-02-03 17:39:11 -03:00
parent c7f8f772c0
commit df085d0e1d
2 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,26 @@
package src.main.java.com.conversions;
import java.math.BigInteger;
public class DecimalToOctal {
private static final char octalChars[] = {'0','1','2','3','4','5','6','7'};
private static final BigInteger valueOctal = new BigInteger("8");
/**
* This method converts and decimal number to a octal number
* @param decimalStr
* @return octal number
*/
public String decimalToOctal(String decimalStr){
BigInteger decimal = new BigInteger(decimalStr);
int rem;
String octal = "";
while(decimal.compareTo(BigInteger.ZERO) > 0) {
rem = decimal.mod(valueOctal).intValueExact();
octal = octalChars[rem] + octal;
decimal = decimal.divide(valueOctal);
}
return octal;
}
}

View File

@ -0,0 +1,16 @@
package src.test.java.com.conversions;
import org.junit.Assert;
import org.junit.Test;
public class DecimalToOctalTest {
@Test
public void testDecimalToOctalTest() {
DecimalToOctal decimalToOctal = new DecimalToOctal();
Assert.assertEquals("Incorrect Conversion", "41", decimalToOctal.decimalToOctal("33"));
Assert.assertEquals("Incorrect Conversion", "5512", decimalToOctal.decimalToOctal("2890"));
Assert.assertEquals("Incorrect Conversion", "12525252525252525252525241", decimalToOctal.decimalToOctal("50371909150609548946081"));
Assert.assertEquals("Incorrect Conversion", "13", decimalToOctal.decimalToOctal("11"));
Assert.assertEquals("Incorrect Conversion", "46703754", decimalToOctal.decimalToOctal("10192876"));
}
}