Merge pull request #703 from arodriguez33/Development

convert decimal to octal
This commit is contained in:
Libin Yang 2019-02-04 08:05:07 +08:00 committed by GitHub
commit edac7f3a5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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"));
}
}