Thursday, 30 November 2023

JAVA

Roman To Numbers



Lets get started

Java code :--

 
         
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Scanner;
  4. public class MINtech {
  5. // Function to convert a Roman numeral to an integer
  6. public static int romanToInt(String s) {
  7. // Create a map to store the values of Roman numerals
  8. Map romanMap = new HashMap<>();
  9. romanMap.put('I', 1);
  10. romanMap.put('V', 5);
  11. romanMap.put('X', 10);
  12. romanMap.put('L', 50);
  13. romanMap.put('C', 100);
  14. romanMap.put('D', 500);
  15. romanMap.put('M', 1000);
  16. // Initialize variables to store the result and the previous value
  17. int result = 0;
  18. int prevValue = 0;
  19. // Iterate through the Roman numeral from right to left
  20. for (int i = s.length() - 1; i >= 0; i--) {
  21. // Get the numeric value of the current Roman numeral character
  22. int value = (int) romanMap.get(s.charAt(i));
  23. // Check if the current value is less than the previous value
  24. if (value < prevValue) {
  25. // If yes, subtract the current value from the result
  26. result -= value;
  27. } else {
  28. // If no, add the current value to the result
  29. result += value;
  30. }
  31. // Update the previous value for the next iteration
  32. prevValue = value;
  33. }
  34. // Return the final result
  35. return result;
  36. }
  37. public static void main(String[] args) {
  38. // Create a scanner to take user input
  39. Scanner scanner = new Scanner(System.in);
  40. // Get user input for a Roman numeral
  41. System.out.print("Enter a Roman numeral: ");
  42. String userInputRoman = scanner.nextLine();
  43. // Convert Roman numeral to integer and print the result
  44. int integerResult = romanToInt(userInputRoman);
  45. System.out.println("Integer: " + integerResult);
  46. // Close the scanner to avoid resource leaks
  47. scanner.close();
  48. }
  49. }

Output




Python code :---

Output

No comments:

Post a Comment