[Leetcode] integer to Roman and Roman to integer

Source: Internet
Author: User

[Question]

Given a roman numeral, convert it to an integer. Or, given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

[Roman numerals]

1 ~ 9: {"I", "II", "III", "IV", "V", "Vi", "VII", "VIII", "IX "};

10 ~ 90: {"X", "XX", "XXX", "XL", "L", "lx", "LXX", "LXXX", "XC "};

100 ~ 900: {"C", "cc", "CCC", "cd", "D", "DC", "DCC", "DCCC", "cm "};

1000 ~ 3000: {"M", "mm", "mmm "}.


[Roman numerals to Integers]

class Solution {public:    int romanToInt(string s) {        int ret = toNumber(s[0]);        for (int i = 1; i < s.length(); i++) {            if (toNumber(s[i - 1]) < toNumber(s[i])) {                ret += toNumber(s[i]) - 2 * toNumber(s[i - 1]);            } else {                ret += toNumber(s[i]);            }        }        return ret;    }        int toNumber(char ch) {        switch (ch) {            case 'I': return 1;            case 'V': return 5;            case 'X': return 10;            case 'L': return 50;            case 'C': return 100;            case 'D': return 500;            case 'M': return 1000;        }        return 0;    }};

[Integer to Roman numerals]

public class Solution {    public String intToRoman(int num) {        String[][] roman = {            {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},            {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},            {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},            {"", "M", "MM", "MMM"}        };                String ret = "";        int digit = 0;        while (num != 0) {            int remain = num % 10;            ret = roman[digit][remain] + ret;            digit++;            num /= 10;        }                return ret;    }}

[Leetcode] integer to Roman and Roman to integer

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.