[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]



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章