Roman to Integer LeetCode Java | Convert Roman Numeral to Integer Value | Programming Tutorials

preview_player
Показать описание
Roman to Integer LeetCode Solution using Java. In this tutorial, I have explained how to convert roman to integer.

Given a Roman numeral, Write a code to convert them into an integer value.
Roman numerals are represented by seven different letters (I, V, X, L, C, D, M).
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

These seven letters are used to make thousand of numbers.


Example 1 -

Input : II
Output : 2

Example 2 -

Input : XI
Output : 11

Example 3 -

Input : VI
Output : 6

Example 4 -

Input : LVII
Output: 57

NOTE - Input is guaranteed to be within the range from 1 to 3999.
Рекомендации по теме
Комментарии
Автор

wowww...its damn clear.... thanks alot !!!

preethishetty
Автор

best explanation ever you made it very simple and clear

sarah-fuhw
Автор

impressed with easily understandable solution

priteshms
Автор

why to traverse till s.lenghth()-1 ; we can directly traverse till end of lenght

yogeshganpule
Автор

great explanation ! sir i have one doubt i.e for string IXX this approach would give value 19 but it should not give 19 because it is not valid . so how to avoid this ???

tilakrajrao
Автор

I tried to run this program but there's an error saying "cannot find symbol Map"

keikei
Автор

why is my code aint working

class Solution {
public int romanToInt(String s) {

Map <Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);

int result = 0;
for (int i=0 ; i<s.length()-1; i++){
if (map.get(s.charAt(i)) >= map.get(s.charAt(i+1))){
result = (map.get(s.charAt(i)) + map.get(s.charAt(i+1)));
}

else if (map.get(s.charAt(i)) <= map.get(s.charAt(i+1))){
result = (map.get(s.charAt(i+1)) - map.get(s.charAt(i)));
}
}

return result ;
}
}

yogeshganpule
Автор

This solution is not working for below input. Please have a look.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

BiswaranjanRoutLucky
Автор

static final Map<Character, Integer> ROMANS = Map.of(
'I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);

public static int convertRomanToInteger(String s) {
int n = 0, p = 0, c;
for (int i = 0, m = s.length(); i < m; ++i, p = c)
n += p >= (c = ROMANS.get(s.charAt(i))) ? p : -p;
return n + p;
}

saka
welcome to shbcf.ru