[LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
2015-03-02 23:19
489 查看
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
代码(github):https://github.com/illuz/leetcode
012. Integer to Roman (Medium) 一样,只要知道转化规则就行了。
Java:
Python:
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
相关文章推荐
- [LeetCode] 009. Palindrome Number (Easy) (C++/Java/Python)
- [LeetCode] 006. ZigZag Conversion (Easy) (C++/Java/Python)
- [LeetCode] 008. String to Integer (Easy) (C++/Java/Python)
- LeetCode 12 — Integer to Roman(C++ Java Python)
- [LeetCode] 007. Reverse Integer (Easy) (C++/Java/Python)
- LeetCode 7 — Reverse Integer(C++ Java Python)
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
- LeetCode 8 — String to Integer (atoi)(C++ Java Python)
- LeetCode题解汇总(C++ Java Python,含题目翻译)
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- LeetCode 15 — 3Sum(C++ Java Python)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- LeetCode 63 — Unique Paths II(C++ Java Python)
- LeetCode 149 — Max Points on a Line(C++ Java Python)
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- LeetCode 62 — Unique Paths(C++ Java Python)
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)