12. Integer to Roman (HashTable)

Given an integer, convert it to a roman numeral.

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

 思路:罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。

第一步,按照千分位,百分位...一一算下来。

class Solution {
public:
    string intToRoman(int num) {
        int quote;
        int residue;
        string ret = "";
        
        //first deal with 10^3
        quote = num/1000;
        residue = num%1000;
        while(quote > 0){
            ret += 'M';
            quote--;
        }
        
        //then deal with 10^2
        quote = residue/100;
        residue %= 100;
        if(quote==9){
            ret += "CM";
        }
        else if(quote >=5){
            ret += 'D';
            while(quote > 5){
                ret += 'C';
                quote--;
            }
        }
        else if(quote==4){
            ret += "CD";
        }
        else{
            while(quote > 0){
                ret += 'C';
                quote--;
            }
        }
        
        //then deal with 10
        quote = residue/10;
        residue %= 10;
        if(quote==9){
            ret += "XC";
        }
        else if(quote >=5){
            ret += 'L';
            while(quote > 5){
                ret += 'X';
                quote--;
            }
        }
        else if(quote==4){
            ret += "XL";
        }
        else{
            while(quote > 0){
                ret += 'X';
                quote--;
            }
        }
        
        //finally deal with 1
        quote = residue;
        if(quote==9){
            ret += "IX";
        }
        else if(quote >=5){
            ret += 'V';
            while(quote > 5){
                ret += 'I';
                quote--;
            }
        }
        else if(quote==4){
            ret += "IV";
        }
        else{
            while(quote > 0){
                ret += 'I';
                quote--;
            }
        }
        
        return ret;
    }
};

第二步,代码有冗余,将其归纳整合。并且用减法代替除法!

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" };
        int size = sizeof(values) / sizeof(values[0]); //获取数组的大小
        string result = "";

        for (int i = 0; i < size; i++) {
            while (num >= values[i]) {
                num -= values[i];
                result+=numerals[i];
            }
        }
        return result;
    }
};

 

posted on 2015-07-21 06:24  joannae  阅读(133)  评论(0编辑  收藏  举报

导航