Monday, May 15, 2017

Roman to Integer


Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Link to GitHubCode



Example
Input : IX
Output : 9

Input : XL
Output : 40

Input : MCMIV
Output :  1904                        C    M
M is a thousand, CM is nine hundred (100-1000)
and IV is four

Overview of Roman Numerals
Symbol I V X L C D M
Value 1 5 10 50 100 500 1,000

Solution

  • Count every symbol add its value to the sum
  • Minus extra part of special cases


public static int get(String s)
 {
  int sum =0;
  //Check the index of these roman charcters
  if(s.indexOf("IV")!=-1) {sum-=2;}
  if(s.indexOf("IX")!=-1) {sum-=2;}
  if(s.indexOf("XL")!=-1) {sum-=20;}
  if(s.indexOf("XC")!=-1) {sum-=20;}
  if(s.indexOf("CD")!=-1) {sum-=200;}
  if(s.indexOf("CM")!=-1) {sum-=200;}
  
  //Convert the string into character array
  char c [] =s.toCharArray();
  int count=0;
  for(;count<=s.length()-1;count++)
  {
   if(c[count]=='M') sum+=1000;
   if(c[count]=='D') sum+=500;
   if(c[count]=='C') sum+=100;
   if(c[count]=='L') sum+=50;
   if(c[count]=='X') sum+=10;
   if(c[count]=='V') sum+=5;
   if(c[count]=='I') sum+=1;
   
  }
  return sum;
 }

Iteration


1 comment: