How to resolve the algorithm Roman numerals/Encode step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Roman numerals/Encode step by step in the Java programming language

Table of Contents

Problem Statement

Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.

In Roman numerals:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Roman numerals/Encode step by step in the Java programming language

First Code

This Java code provides a function to convert a long integer to its Roman numeral representation. It defines an enum for the Roman numerals and their corresponding weights and uses a loop to iteratively append the largest applicable Roman numeral to a StringBuilder until the number reaches 0.

  • Class Definition: The RN class contains the code for converting numbers to Roman numerals.

  • Numeral Enum: This is an enum that lists the Roman numerals and their corresponding weights. It provides a constructor to initialize the weight field for each numeral.

  • roman Method: This method takes a long integer n as input and returns its Roman numeral representation. It validates the input to ensure it's greater than 0. Then, it uses a for loop to iterate through the Numeral values in descending order. Within the loop, it continues to append the largest applicable Roman numeral to a StringBuilder until n becomes 0.

  • test Method: This method is used for testing the roman method with different input numbers.

  • main Method: The main method calls the test method for various input numbers, such as 1999, 25, and 944, to demonstrate the conversion.

Second Code

This Java code provides a more comprehensive interface for working with Roman numerals. It includes methods for both encoding (converting integers to Roman numerals) and decoding (converting Roman numerals to integers).

  • Numeral Enum: This enum lists the Roman numerals and their corresponding weights. It includes a method getLargest that returns the largest numeral that is less than or equal to a given weight.

  • encode Method: This method takes a long integer n and returns its Roman numeral representation. It uses an infinite stream to iteratively subtract the largest applicable Roman numeral from n until n reaches 0. For each iteration, it maps the weight to the corresponding Numeral and appends its string representation to the result.

  • decode Method: This method takes a Roman numeral string roman and returns its integer representation. It reverses the string, iterates through each character, converts it to a Numeral, and adds its weight to the result. If the first two characters in the string are the same, it adds double the weight of the corresponding numeral to the result.

  • test Method: This method is used for testing the encode and decode methods with different input values.

  • main Method: The main method calls the test method for various input numbers, such as 1999, 25, and 944, to demonstrate the encoding and decoding functionality.

Source code in the java programming language

public class RN {

    enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {
        
        if( n <= 0) {
            throw new IllegalArgumentException();
        }
        
        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }

}

import java.util.Set;
import java.util.EnumSet;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public interface RomanNumerals {
  public enum Numeral {
    M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);

    public final long weight;

    private static final Set<Numeral> SET = Collections.unmodifiableSet(EnumSet.allOf(Numeral.class));

    private Numeral(long weight) {
      this.weight = weight;
    }

    public static Numeral getLargest(long weight) {
      return SET.stream()
        .filter(numeral -> weight >= numeral.weight)
        .findFirst()
        .orElse(I)
      ;
    }
  };

  public static String encode(long n) {
    return LongStream.iterate(n, l -> l - Numeral.getLargest(l).weight)
      .limit(Numeral.values().length)
      .filter(l -> l > 0)
      .mapToObj(Numeral::getLargest)
      .map(String::valueOf)
      .collect(Collectors.joining())
    ;
  }

  public static long decode(String roman) {
    long result =  new StringBuilder(roman.toUpperCase()).reverse().chars()
      .mapToObj(c -> Character.toString((char) c))
      .map(numeral -> Enum.valueOf(Numeral.class, numeral))
      .mapToLong(numeral -> numeral.weight)
      .reduce(0, (a, b) -> a + (a <= b ? b : -b))
    ;
    if (roman.charAt(0) == roman.charAt(1)) {
      result += 2 * Enum.valueOf(Numeral.class, roman.substring(0, 1)).weight;
    }
    return result;
  }

  public static void test(long n) {
    System.out.println(n + " = " + encode(n));
    System.out.println(encode(n) + " = " + decode(encode(n)));
  }

  public static void main(String[] args) {
    LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
  }
}

  

You may also check:How to resolve the algorithm Number names step by step in the Inform 7 programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the Haskell programming language
You may also check:How to resolve the algorithm Forward difference step by step in the C programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the Maple programming language
You may also check:How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the FreeBASIC programming language