zoukankan      html  css  js  c++  java
  • [LeetCode] Roman to Integer

    Given a roman numeral, convert it to an integer.

    Input is guaranteed to be within the range from 1 to 3999.

    将一串罗马数字转换为整数,首先使用map建立罗马字母与数字的表示法则。然后从右向左遍历罗马字符串,根据罗马计数法则:

    1)相同的数字连写,所表示的数等于这些数字相加得到的数。

    2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数。

    3)小的数字(仅限L, X, C)在大的数字左边,所表示的数等于大数减去小数得到的数。

    用if语句判断1),2)和3)即可。

    class Solution {
    public:
        int romanToInt(string s) {
            unordered_map<char, int> m = {{'I', 1}, 
                                          {'V', 5}, 
                                          {'X', 10}, 
                                          {'L', 50}, 
                                          {'C', 100}, 
                                          {'D', 500}, 
                                          {'M', 1000}
                                         };
            int n = s.size();
            int res = m[s[n - 1]];
            for (int i = n - 2; i >= 0; i--) {
                if (m[s[i]] < m[s[i + 1]])
                    res -= m[s[i]];
                else
                    res += m[s[i]];
            }
            return res;
        }
    };
    // 105 ms
  • 相关阅读:
    Java工具类——UUIDUtils
    Python中的split()函数的用法
    学习笔记
    hdu 1558 线段相交+并查集
    hdu 4609 FFT
    hdu1402 FFT入门
    多项式乘法快速算法
    FFT
    GDUT校赛
    light oj 1236 分解质因数
  • 原文地址:https://www.cnblogs.com/immjc/p/7194822.html
Copyright © 2011-2022 走看看