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
  • 相关阅读:
    mysql总结
    git总结
    转:如何判断一家公司的好坏
    路越走越窄,尤其做技术的
    百度面试总结
    背叛
    which和whereis 命令
    bzoj3263 陌上花开 CDQ模板
    bzoj 2653middle
    暑假第十九测
  • 原文地址:https://www.cnblogs.com/immjc/p/7194822.html
Copyright © 2011-2022 走看看