Wednesday, February 9, 2022

Roman to decimal conversion

       
       
class Solution {
   public static void main(String[] args) {
    System.out.println("Should be (3). ="+new Solution().romanToInt("III"));
     
      System.out.println("Should be (58). ="+new Solution().romanToInt("LVIII"));
      System.out.println("Should be (1994). ="+new Solution().romanToInt("MCMXCIV"));
  }
    public int romanToInt(String s) {
        Map romanValues = new HashMap();
        romanValues.put("I", "1");
        romanValues.put("V", "5");
        romanValues.put("X", "10");
        romanValues.put("L", "50");
        romanValues.put("C", "100");
        romanValues.put("D", "500");
        romanValues.put("M", "1000");
        String romanNum = s;
        int intValue=0;
        int prevValue=0;
        for(int i=0; i< s.length(); i++){
            String firstChar = romanNum.substring(0,1);
            if(firstChar==null)
                continue;
           System.out.println("firstChar= "+firstChar);
            
            int romanIntValue= Integer.valueOf((String)romanValues.get(firstChar));
           System.out.println("romanIntValue= "+romanIntValue);
          if(romanIntValue > prevValue){
            romanIntValue -=prevValue;
            intValue -=prevValue;
          }
            
           prevValue=romanIntValue;
            intValue +=romanIntValue;
           System.out.println("intValue= "+intValue);
          
          romanNum = romanNum.substring(1, romanNum.length());
           System.out.println("romanNum= "+romanNum);
        }
        return intValue;
    }
}
       

No comments: