package com.freetymekiyan.algorithms.level.easy;

/**
 * Given a roman numeral, convert it to an integer.
 * <p>
 * Input is guaranteed to be within the range from 1 to 3999.
 * <p>
 * Company Tags: Microsoft, Bloomberg, Uber, Facebook, Yahoo
 * Tags: Math, String
 * Similar Problems: (M) Integer to Roman
 */
public class RomanToInteger {

    char[] roman = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
    int[] val = {1, 5, 10, 50, 100, 500, 1000};

    /**
     * String, Math.
     * First need to know how many these letters are, respectively.
     * Then need to clarify whether the input can be negative, or there is only uppercase.
     * <p>
     * Traverse the characters backwards.
     * Add the value to result according to characters.
     * C = 100 X = 10 I = 1 are special
     * Compare with 500, 50 and 5
     * If bigger, it means current value is negative
     */
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int res = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            switch (c) {
                case 'M':
                    res += 1000;
                    break;
                case 'D':
                    res += 500;
                    break;
                case 'C':
                    res += 100 * (res >= 500 ? -1 : 1); // For CD or CM
                    break;
                case 'L':
                    res += 50;
                    break;
                case 'X':
                    res += 10 * (res >= 50 ? -1 : 1); // For XL or XC
                    break;
                case 'V':
                    res += 5;
                    break;
                case 'I':
                    res += (res >= 5 ? -1 : 1); // For IV or IX
                    break;
                default:
                    break;
            }
        }
        return res;
    }
}

@@ -499,48 +499,35 @@
 now 
-how many these letters are, respectively
+the letter to value mapping
 .%0A  
@@ -574,14 +574,23 @@
 put 
-can be
+string can mean
  neg
@@ -646,49 +646,58 @@
   * 
-Traverse the characters backwards.
+For each character from the end to front:
 %0A     *
+ %7C
  Add
@@ -730,16 +730,20 @@
 ding to 
+the 
 characte
@@ -743,17 +743,16 @@
 haracter
-s
 .%0A     *
@@ -756,55 +756,70 @@
   * 
-C = 
+%7C Only when for C=
 100 X
- = 
+=
 10 I
- = 1 are special%0A     * Compare
+=1, need to compare current number
  wit
@@ -837,61 +837,111 @@
 nd 5
+.
 %0A     *
+ %7C
  If 
-bigger, it means current value is negative
+result is larger or equal, they mean negative values.%0A     * %7C Subtract them from result.
 %0A   
@@ -1459,16 +1459,17 @@
 CD or CM
+.
 %0A       
@@ -1667,16 +1667,17 @@
 XL or XC
+.
 %0A       
@@ -1868,16 +1868,17 @@
 IV or IX
+.
 %0A       

update roman integer