From df085d0e1dee6952f45512511a4e3a97a2368f29 Mon Sep 17 00:00:00 2001 From: Adan Rodriguez Date: Sun, 3 Feb 2019 17:39:11 -0300 Subject: [PATCH] convert decimal to octal value --- .../java/com/conversions/DecimalToOctal.java | 26 +++++++++++++++++++ .../com/conversions/DecimalToOctalTest.java | 16 ++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/main/java/com/conversions/DecimalToOctal.java create mode 100644 src/test/java/com/conversions/DecimalToOctalTest.java diff --git a/src/main/java/com/conversions/DecimalToOctal.java b/src/main/java/com/conversions/DecimalToOctal.java new file mode 100644 index 00000000..743b0e0a --- /dev/null +++ b/src/main/java/com/conversions/DecimalToOctal.java @@ -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; + } +} diff --git a/src/test/java/com/conversions/DecimalToOctalTest.java b/src/test/java/com/conversions/DecimalToOctalTest.java new file mode 100644 index 00000000..1916b7ef --- /dev/null +++ b/src/test/java/com/conversions/DecimalToOctalTest.java @@ -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")); + } +}