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

Source: Internet
Author: User

[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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.