Roman To Integer

Problem:

Convert a given roman number to an integer.

Example:
Input: "III" Output: 3
Input: "IV" Output: 4
Input: "IX" Output: 9
Input: "LVIII" Output: 58
Input: "MCMXCIV" Output: 1994
Given:
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

Solution:

public class RomanToInteger {

	public static int romanToInt(String s) {
		int sum = 0;
		char arr[] = s.toCharArray();
		for (int i = arr.length - 1; i >= 0; i--) {
			int temp = 0;
			temp = roman.valueOf(String.valueOf(arr[i])).getValue();
			System.out.println(roman.valueOf(String.valueOf(arr[i])));
			if (i != 0 &amp;&amp; roman.valueOf(String.valueOf(arr[i - 1])).getValue() < temp) {
				temp = temp - roman.valueOf(String.valueOf(arr[i - 1])).getValue();
				i--;
			}
			sum += temp;
		}
		return sum;
	}

	public static void main(String args[]) {
		System.out.println(romanToInt("III"));
	}
}

enum roman {
	I("I", 1), V("V", 5), X("X", 10), L("L", 50), C("C", 100), D("D", 500), M("M", 1000);
	
	String symbol;
	Integer value;

	roman(String s, Integer v) {
		this.symbol = s;
		this.value = v;
	}

	public Integer getValue() {
		return value;
	}
}

Explanation:

Second last number

Time and Space:

Time: O(N) and Space: O(1)
Explanation:

(Visited 6 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
22 + 3 =