[leetcode] integer 与 Roman的转换

1. integer到roman

利用了数组的位置的信息

class Solution {
public:
    string intToRoman(int num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        char dictionary[8] = {'I','V','X','L','C','D','M'};
        string result;
        int scale = 1000;
        int dictLoct = 6;
        while (scale> 0){
            int value = num/scale;
            intToRomanHelper(value,result,dictionary,dictLoct);
            num %= scale;
            scale /=10;
            dictLoct -=2;
        }
        return result;
    }
    
    void intToRomanHelper(int num,string& result,char* dictionary,int dictLoct){
        if (num==0)
            return;
        else if(num<4){
            result.append(num,dictionary[dictLoct]);
        } 
        else if (num == 4){
            result.append(1,dictionary[dictLoct]);
            result.append(1,dictionary[dictLoct+1]);
        }
        else if (num < 9){
            result.append(1,dictionary[dictLoct+1]);
            result.append(num-5,dictionary[dictLoct]);
        }
        else{
            result.append(1,dictionary[dictLoct]);
            result.append(1,dictionary[dictLoct+2]);
        }
    }
};
string append的用法

2. roman 到integer

wikipedia:http://en.wikipedia.org/wiki/Roman_number

class Solution {
public:
    int romanToInt(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = s.size();
        if (len == 0)
            return 0;
            
        map<char,int> dict;
        dict['I'] = 1;
        dict['V'] = 5;
        dict['X'] = 10;
        dict['L'] = 50;
        dict['C'] = 100;
        dict['D'] = 500;
        dict['M'] = 1000;
        int result=0;
        
        for(int i = 0; i<len; i++){
            result += romanSymbol(dict,s,i)*dict[s[i]];
        }
        
        return result;
    }
    
    int romanSymbol(map<char,int> dict,string s,int index){
        if (index+1 == s.size()){
            return 1;
        }
        
        if (dict[s[index]]<dict[s[index+1]])
            return -1;
        else
            return 1;
    }
};
roman字母也是从高位到低位排列,总结规律:只要前面一个数,比后面一个数小,则减去这个数;否则都是加法。

注意:dict[s[index]] 老写错,写成s[index]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值