13. Roman to Integer[E]罗马数字转整数

题目

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


Tips

C++知识

map

1. 定义
所有元素都是pair,同时拥有键值(key)和实值(value),第一个元素作为键值keymap不允许有相同的键值,第二个值是key对应的value值。key和value可以是任意需要的类型。
2. 构造函数
map<int, string> newMap;
3. 添加数据

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

Python知识

for循环

1. 循环定义
for anElement in object:
对象Object是一个集合,可以遍历每一个元素
2. 利用range生成整数序列

  • 三个参数:起始值、终值、步长
    • 起始值如果不提供则默认为0
    • 终值是必须的参数,如果只有一个参数,那么该参数就是终值
    • 步长默认为1,只有提供三个参数时,才有步长值
    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. 不能改变变量值
    在python中,for循环相当于一个迭代器,在循环体改变循环变量的值对循环次数是没有影响的。因此,对于需要改变变量值的,可以改用while循环。

    词典结构

    利用查找键值来查找对应的实值


思路

在进行罗马数字转化为整数的过程中,由于罗马数字是按照从左往右从大到小的顺序排列,于是可以分析,当左边罗马数字对应的整数A比右边一个罗马数字对应的整数B小的时候,表示B-A。
利用map建立一个罗马数字与整数的对应映射,检查字符串当前字符与下一个字符对应整数的大小关系。
这种建立查找表的题可以通过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

猜你喜欢

转载自www.cnblogs.com/Jessey-Ge/p/10993464.html
今日推荐