Skip to content

Commit ec30592

Browse files
authored
refactor: DecimalToOctal (#5332)
1 parent a84a4a2 commit ec30592

File tree

2 files changed

+42
-21
lines changed

2 files changed

+42
-21
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
package com.thealgorithms.conversions;
22

3-
import java.util.Scanner;
4-
53
/**
64
* This class converts Decimal numbers to Octal Numbers
75
*/
86
public final class DecimalToOctal {
7+
private static final int OCTAL_BASE = 8;
8+
private static final int INITIAL_OCTAL_VALUE = 0;
9+
private static final int INITIAL_PLACE_VALUE = 1;
10+
911
private DecimalToOctal() {
1012
}
1113

1214
/**
13-
* Main Method
15+
* Converts a decimal number to its octal equivalent.
1416
*
15-
* @param args Command line Arguments
17+
* @param decimal The decimal number to convert.
18+
* @return The octal equivalent as an integer.
19+
* @throws IllegalArgumentException if the decimal number is negative.
1620
*/
21+
public static int convertToOctal(int decimal) {
22+
if (decimal < 0) {
23+
throw new IllegalArgumentException("Decimal number cannot be negative.");
24+
}
25+
26+
int octal = INITIAL_OCTAL_VALUE;
27+
int placeValue = INITIAL_PLACE_VALUE;
1728

18-
// enter in a decimal value to get Octal output
19-
public static void main(String[] args) {
20-
Scanner sc = new Scanner(System.in);
21-
int n;
22-
int k;
23-
int d;
24-
int s = 0;
25-
int c = 0;
26-
System.out.print("Decimal number: ");
27-
n = sc.nextInt();
28-
k = n;
29-
while (k != 0) {
30-
d = k % 8;
31-
s += d * (int) Math.pow(10, c++);
32-
k /= 8;
29+
while (decimal != 0) {
30+
int remainder = decimal % OCTAL_BASE;
31+
octal += remainder * placeValue;
32+
decimal /= OCTAL_BASE;
33+
placeValue *= 10;
3334
}
3435

35-
System.out.println("Octal equivalent:" + s);
36-
sc.close();
36+
return octal;
3737
}
3838
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.CsvSource;
9+
10+
class DecimalToOctalTest {
11+
@ParameterizedTest
12+
@CsvSource({"0, 0", "7, 7", "8, 10", "10, 12", "64, 100", "83, 123", "7026, 15562"})
13+
void testConvertToOctal(int decimal, int expectedOctal) {
14+
assertEquals(expectedOctal, DecimalToOctal.convertToOctal(decimal));
15+
}
16+
17+
@Test
18+
void testConvertToOctalNegativeNumber() {
19+
assertThrows(IllegalArgumentException.class, () -> DecimalToOctal.convertToOctal(-10));
20+
}
21+
}

0 commit comments

Comments
 (0)