Skip to content

Commit df085d0

Browse files
committed
convert decimal to octal value
1 parent c7f8f77 commit df085d0

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package src.main.java.com.conversions;
2+
3+
import java.math.BigInteger;
4+
5+
public class DecimalToOctal {
6+
private static final char octalChars[] = {'0','1','2','3','4','5','6','7'};
7+
private static final BigInteger valueOctal = new BigInteger("8");
8+
9+
/**
10+
* This method converts and decimal number to a octal number
11+
* @param decimalStr
12+
* @return octal number
13+
*/
14+
public String decimalToOctal(String decimalStr){
15+
BigInteger decimal = new BigInteger(decimalStr);
16+
17+
int rem;
18+
String octal = "";
19+
while(decimal.compareTo(BigInteger.ZERO) > 0) {
20+
rem = decimal.mod(valueOctal).intValueExact();
21+
octal = octalChars[rem] + octal;
22+
decimal = decimal.divide(valueOctal);
23+
}
24+
return octal;
25+
}
26+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package src.test.java.com.conversions;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class DecimalToOctalTest {
7+
@Test
8+
public void testDecimalToOctalTest() {
9+
DecimalToOctal decimalToOctal = new DecimalToOctal();
10+
Assert.assertEquals("Incorrect Conversion", "41", decimalToOctal.decimalToOctal("33"));
11+
Assert.assertEquals("Incorrect Conversion", "5512", decimalToOctal.decimalToOctal("2890"));
12+
Assert.assertEquals("Incorrect Conversion", "12525252525252525252525241", decimalToOctal.decimalToOctal("50371909150609548946081"));
13+
Assert.assertEquals("Incorrect Conversion", "13", decimalToOctal.decimalToOctal("11"));
14+
Assert.assertEquals("Incorrect Conversion", "46703754", decimalToOctal.decimalToOctal("10192876"));
15+
}
16+
}

0 commit comments

Comments
 (0)