Roman Number to Integer
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Convert Roman numeral to integer. Scan right to left; subtract if current < next, else add.
Algorithm
- 1Map each symbol to value. Scan from right. If val < prevVal: subtract. Else add. Track prevVal.
Common Pitfalls
- •Same as LC 13. Subtractive notation: IV=4, IX=9 etc. Right-to-left scan handles this naturally.
Roman Number to Integer.java
Java
// Approach: HashMap for values. Subtract current if next is larger, otherwise add.
// Time: O(n) Space: O(1)
import java.util.*;
class Solution {
public int romanToDecimal(String s) {
HashMap<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 ans = 0;
for (int i = 0; i < s.length() - 1; i++) {
int num1 = map.get(s.charAt(i));
int num2 = map.get(s.charAt(i + 1));
if (num1 >= num2)
ans += num1;
else
ans -= num1;
}
return ans + map.get(s.charAt(s.length() - 1));
}
}Advertisement
Was this solution helpful?