[LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


013.Roman_to_Integer (Easy)

链接

题目:https://oj.leetcode.com/problems/roman-to-integer/
代码(github):https://github.com/illuz/leetcode

题意

把罗马数转为十进制。

分析

跟 012. Integer to Roman (Medium) 一样,只要知道转化规则就行了。

代码

C++:

class Solution {
private:
	int val[255];
	void init() {
		val['I'] = 1; val['V'] = 5; val['X'] = 10; val['L'] = 50;
		val['C'] = 100; val['D'] = 500; val['M'] = 1000;
	}
public:
    int romanToInt(string s) {
		init();
		int ret = 0;
		for (int i = 0; i < s.size(); i++) {
			if (i > 0 && val[s[i]] > val[s[i - 1]]) {
				ret += val[s[i]] - 2 * val[s[i - 1]];
			} else {
				ret += val[s[i]];
			}
		}
		return ret;
    }
};


Java:

public class Solution {
    private int[] val = new int[255];
    private void init() {
        val['I'] = 1; val['V'] = 5; val['X'] = 10; val['L'] = 50;
        val['C'] = 100; val['D'] = 500; val['M'] = 1000;
    }

    public int romanToInt(String s) {
        init();
        int ret = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i > 0 && val[s.charAt(i)] > val[s.charAt(i - 1)]) {
                ret += val[s.charAt(i)] - 2 * val[s.charAt(i - 1)];
            } else {
                ret += val[s.charAt(i)];
            }
        }
        return ret;
    }
}


Python:

class Solution:
    # @return an integer
    def romanToInt(self, s):
        val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        ret = 0
        for i in range(len(s)):
            if i > 0 and val[s[i]] > val[s[i - 1]]:
                ret += val[s[i]] - 2 * val[s[i - 1]]
            else:
                ret += val[s[i]]
        return ret


你可能感兴趣的:(java,LeetCode,C++,算法,python)