Write a program to convert roman to an integer.
Example 1:
Input: s = "IX"
Output: 9
Example 2:
Input: s = "IV"
Output: 4
Approach
Java
import java.util.HashMap;public class RomanToInteger {static HashMap<String, Integer> romanInt = new HashMap<>();public static void main(String[] args) {mapRomanToInt();String roman = "IX";int romanV = romanToInt(roman);System.out.println("Roman " + roman + " integer is " + romanV);}private static int romanToInt(String roman) {int res = 0;// iterate all roman element till endfor (int i = 0; i < roman.length(); i++) {// First elementif (i == 0) {res = romanInt.get(String.valueOf(roman.charAt(i)));} else {int current = romanInt.get(String.valueOf(roman.charAt(i)));int prev = romanInt.get(String.valueOf(roman.charAt(i - 1)));// current element is greater then previousif (current > prev) {res += current - 2 * prev;} else {res += current;}}}return res;}/*** @Desc: create roman and int map*/private static void mapRomanToInt() {romanInt.put("I", 1);romanInt.put("V", 5);romanInt.put("X", 10);romanInt.put("L", 50);romanInt.put("C", 100);romanInt.put("D", 500);romanInt.put("M", 1000);}}
C++
#include <bits/stdc++.h>using namespace std;int romanToInteger(string s){//unordered map to hold all//characters numerical valuesunordered_map<char,int> ump;ump['I']=1;ump['V']=5;ump['X']=10;ump['L']=50;ump['C']=100;ump['D']=500;ump['M']=1000;int res=0;for(int i=0;i<s.size();i++){// i =0 res=currif(i==0)res+=ump[s[i]];else{int y=ump[s[i]];int x=ump[s[i-1]];//if curr is greater than previous//then res=res+curr-2*previf(y>x)res+=y-2*x;//else res=res+currelseres+=y;}}//return the resultreturn res;}int main(){string roman="IX";int integer=romanToInteger(roman);cout<<"Integer is ";cout<<integer<<"\n";return 0;}//Time Complexity:O(n)
No comments:
Post a Comment