13. Roman to Integer [E] digital-to-integer Rome

topic

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


Tips

C ++ knowledge

map

1. Define
all elements are pair, at the same time has a key ( key) and a real value ( value), the first element as a key key, mapnot have the same key value, the second value is a value corresponding to the key value. key and value can be any type of need.
2. constructor
map<int, string> newMap;
3. Add Data

map<int, string> newMap;
pair<int , string> add(1,"a");
newMap.insert(add);

Python Knowledge

for loop

1. The cycle definition
for anElement in object:
Object An object is a collection, each element can be traversed
2. Use range produces a sequence of integers

  • Three parameters: start value, the final value, step
    • If you do not provide the default start value is 0
    • The final parameter value is a must, if only one parameter, the parameter is the final value
    • The default is 1 step, provided only three parameters, only the step value
    range(5)
    [0, 1, 2, 3, 4]
    range(3,8)
    [3, 4, 5, 6, 7]
    range(1,20,4)
    [1, 5, 9, 13, 17]

    3. The variable value can not be changed
    in python, iterator for a loop corresponding to changes in the value of the loop variable of loop cycles is not affected. Thus, the need to change the variable value, while loop can be used instead.

    Dictionary structure

    Using the lookup key to find the corresponding real-valued


Thinking

Performing digital conversion process integer Rome, since Roman numerals from left to right are arranged in descending order, can then be analyzed, when the Roman numeral on the left than the right one integer A Roman numeral small integer B when representing BA.
Using the map to create a map corresponding to the Roman numerals with integers, check the current character string with the next character correspondence relationship between the size of an integer.
This look-up table established problem can be resolved by map.

C++

int romanToInt(string s){
  map<char, int> table={{'I', 1}, {'V', 5}, {'X',10}, {'L', 50}, {'C',100}, {'D', 500}, {'M', 1000}};
  int resVal = 0;
  for(int i= 0; i < s.length(); i++){
    if(i+1 <s.length() && table[s.at(i)] < table[s.at(i+1)]){
      resVal += table[s.at(i+1)] - table[s.at(i)];
      i++;
      continue;
    }
    resVal += table[s.at(i)];
  }
  return resVal;
}

Python

 def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        table = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        resInt = 0
        i = 0
        while i < len(s):
            if i > 0 and  table[s[i]] >  table[s[i - 1]]:
                resInt +=  table[s[i]] - 2 *  table[s[i - 1]]
            else:
                resInt +=  table[s[i]]
            i += 1
        return resInt

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993464.html