- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
-
- public class MINtech {
-
- // Function to convert a Roman numeral to an integer
- public static int romanToInt(String s) {
- // Create a map to store the values of Roman numerals
- Map romanMap = new HashMap<>();
- romanMap.put('I', 1);
- romanMap.put('V', 5);
- romanMap.put('X', 10);
- romanMap.put('L', 50);
- romanMap.put('C', 100);
- romanMap.put('D', 500);
- romanMap.put('M', 1000);
-
- // Initialize variables to store the result and the previous value
- int result = 0;
- int prevValue = 0;
-
- // Iterate through the Roman numeral from right to left
- for (int i = s.length() - 1; i >= 0; i--) {
- // Get the numeric value of the current Roman numeral character
- int value = (int) romanMap.get(s.charAt(i));
-
- // Check if the current value is less than the previous value
- if (value < prevValue) {
- // If yes, subtract the current value from the result
- result -= value;
- } else {
- // If no, add the current value to the result
- result += value;
- }
-
- // Update the previous value for the next iteration
- prevValue = value;
- }
-
- // Return the final result
- return result;
- }
-
- public static void main(String[] args) {
- // Create a scanner to take user input
- Scanner scanner = new Scanner(System.in);
-
- // Get user input for a Roman numeral
- System.out.print("Enter a Roman numeral: ");
- String userInputRoman = scanner.nextLine();
-
- // Convert Roman numeral to integer and print the result
- int integerResult = romanToInt(userInputRoman);
- System.out.println("Integer: " + integerResult);
-
- // Close the scanner to avoid resource leaks
- scanner.close();
- }
- }
No comments:
Post a Comment