[LeetCode] 013. Roman to Integer (Easy) (C ++/Java/Python), leetcodepython
Index: [LeetCode] Leetcode index (C ++/Java/Python/SQL)
Github: https://github.com/illuz/leetcode
013. Roman_to_Integer (Easy)
Link:
Title: https://oj.leetcode.com/problems/roman-to-integer/
Code (github): https://github.com/illuz/leetcode
Question:
Convert the number of Rome to decimal.
Analysis:
Like 012. Integer to Roman (Medium), you only need to know the conversion rules.
Code:
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