Skip to content

refactor: DecimalToOctal #5332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions src/main/java/com/thealgorithms/conversions/DecimalToOctal.java
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
package com.thealgorithms.conversions;

import java.util.Scanner;

/**
* This class converts Decimal numbers to Octal Numbers
*/
public final class DecimalToOctal {
private static final int OCTAL_BASE = 8;
private static final int INITIAL_OCTAL_VALUE = 0;
private static final int INITIAL_PLACE_VALUE = 1;

private DecimalToOctal() {
}

/**
* Main Method
* Converts a decimal number to its octal equivalent.
*
* @param args Command line Arguments
* @param decimal The decimal number to convert.
* @return The octal equivalent as an integer.
* @throws IllegalArgumentException if the decimal number is negative.
*/
public static int convertToOctal(int decimal) {
if (decimal < 0) {
throw new IllegalArgumentException("Decimal number cannot be negative.");
}

int octal = INITIAL_OCTAL_VALUE;
int placeValue = INITIAL_PLACE_VALUE;

// enter in a decimal value to get Octal output
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
int k;
int d;
int s = 0;
int c = 0;
System.out.print("Decimal number: ");
n = sc.nextInt();
k = n;
while (k != 0) {
d = k % 8;
s += d * (int) Math.pow(10, c++);
k /= 8;
while (decimal != 0) {
int remainder = decimal % OCTAL_BASE;
octal += remainder * placeValue;
decimal /= OCTAL_BASE;
placeValue *= 10;
}

System.out.println("Octal equivalent:" + s);
sc.close();
return octal;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.thealgorithms.conversions;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class DecimalToOctalTest {
@ParameterizedTest
@CsvSource({"0, 0", "7, 7", "8, 10", "10, 12", "64, 100", "83, 123", "7026, 15562"})
void testConvertToOctal(int decimal, int expectedOctal) {
assertEquals(expectedOctal, DecimalToOctal.convertToOctal(decimal));
}

@Test
void testConvertToOctalNegativeNumber() {
assertThrows(IllegalArgumentException.class, () -> DecimalToOctal.convertToOctal(-10));
}
}