算法:罗马数字和整型的相互转换

算法 - 罗马数字和整型的相互转换

罗马符号对应数字
I1
V5
X10
L50
C100
D500
M1000

基本规则:

小数+大数:后者减前者,但不可跨越一个位值,如 8(VIII)不能是IIX
大数+小数:两者相加,但右加数字不可连续超过三位,如9(IX)不能是VIIII

1、Roman To Integer

class Solution {
public:
    /**
     * @param s: Roman representation
     * @return: an integer
     */
    int romanToInt(string &s) {
        // write your code here
        int n = s.length();
        if(n==0)
        	return 0;
        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 ans = 0;
        for(int i=0; i<n; i++){
        	if(i+1<n && m[s[i]]<m[s[i+1]]){
        	    ans -= m[s[i]];
        	}else{
        		ans += m[s[i]];
        	}
        }
        return ans;
    }
};

比较直观,只需要遍历所有位置,判断是要加还是减


2、Integer To Roman

class Solution {
public:
    /**
     * @param n: The integer
     * @return: Roman representation
     */
    string intToRoman(int n) {
        // write your code here
        vector<int> cases = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 ,1};
        vector<string> symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        string ans = "";
        for(int i=0; i<cases.size(); i++){
            int num = n/cases[i];
            while(num--){
                ans += symbols[i];
                n -= cases[i];
            }
        }
        return ans;
    }
};

前提条件: n 在1~3999范围内

列出需要判断的特殊条件,再用循环比较高效和方便


题目列表:
https://www.lintcode.com/problem/integer-to-roman/description
https://www.lintcode.com/problem/roman-to-integer/description

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值