【Leetcode长征系列】Roman to Integer && Integer to Roman

来源:互联网 发布:qq间谍软件 编辑:程序博客网 时间:2024/05/21 11:04

原题:

Given a roman numeral, convert it to an integer.

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

I - 1V - 5X - 10L - 50C - 100D - 500M - 1000If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.So 'IV' is '4' and 'VI' is '6'.For the numbers above X, only the symbol right before it may be subtracted: so 99 is: XCIX (and not IC).

相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3

小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8

小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4

正常使用时,连续的数字重复不得超过三次在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)


思路:知道了罗马数字的表现规则后就很好办了。关于如何存储罗马数字与数字的对应关系,网上有的人用switch来返回int值,新建一个函数。但实际上STL里已经给我们提供了一个非常好的方法,map。

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

AC了,这里需要注意i=0的情况!

=================================================================================================================================

原题:

Given an integer, convert it to a roman numeral.

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

比较现有数字与values数组里的值(从大到小),减去一个values的值增加一个对应位置的numeral符号。

class Solution {public:    string intToRoman(int num) {        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};        string numerals[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };        string res="";                for(int i = 0;  i<13 ; i++){            while(values[i]<=num && num!=0){                num -= values[i];                res = res+numerals[i];            }        }        return res;    }};





0 0
原创粉丝点击