文章标题

来源:互联网 发布:js childnodes方法 编辑:程序博客网 时间:2024/06/03 02:26

12. Integer to Roman

Given an integer, convert it to a roman numeral.

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

这里写图片描述

由上图可知,数字都可由1,4,5,9,10,40,50,90,100,400,500,900,1000构成;

string intToRoman(int num) {    string symbal[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };    int value[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };    string str = "";    for (int i = 0; num != 0; i++){        while (num >= value[i]){            str += symbal[i];            num -= value[i];        }    }    return str;}

13. Roman to Integer

Given a roman numeral, convert it to an integer.

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

int romanToInt(string s) {    map<char, int> res = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 },                           { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };    int sum = res[s[0]];    for (int i = 1; i < s.size(); i++){        if (res[s[i - 1]] < res[s[i]])            sum += res[s[i]] - 2 * res[s[i - 1]];        else            sum += res[s[i]];    }    return sum;}