Roman to Integer in JAVA

Roman to Integer in JAVA

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

class RomanToInteger{
    
     int value(char r)
	    {
		if (r == 'I')
			return 1;
		if (r == 'V')
			return 5;
		if (r == 'X')
			return 10;
		if (r == 'L')
			return 50;
		if (r == 'C')
			return 100;
		if (r == 'D')
			return 500;
		if (r == 'M')
			return 1000;
		return -1;
	}
      
    public int romanToInt(String s) {
      
         
        
       int res = 0;

		for (int i = 0; i < s.length(); i++) 
		{
			// Getting value of symbol s[i]
			int s1 = value(s.charAt(i));

			// Getting value of symbol s[i+1]
			if (i + 1 < s.length()) 
			{
				int s2 = value(s.charAt(i + 1));

				// Comparing both values
				if (s1 >= s2) 
				{
					// Value of current symbol
					// is greater or equalto
					// the next symbol
					res = res + s1;
				}
				else
				{
					// Value of current symbol is
					// less than the next symbol
					res = res + s2 - s1;
					i++;
				}
			}
			else {
				res = res + s1;
			}
		}

		return res;
        
        
        
    }
}

0 Comments

Leave a reply

* Your email/mobile address will not be published. required fields are marked.

* Email and mobile number will be verified before publishing the comments.

Name *
Email *
Mobile