Converting integer to Roman Numeral

前端 未结 9 1311
轮回少年
轮回少年 2020-12-16 08:27

I have a test due in about four hours and one of the questions asks us to convert a user-inputed integer up to 100 into a roman numeral. I think my code is very close (I fou

9条回答
  •  眼角桃花
    2020-12-16 08:43

    I wrote this for fun; maybe useful. Note however, that it will not work for values greater than 1000. Can adapt it to suit your needs though. Here you go:

    enum roman_digits{
        I=1,
        V=5,
        X=10,
        L=50,
        C=100,
        D=500,
        M=1000
    };
    
    std::string lookup(roman_digits v) {
        switch (v) {
        case I:
            return "I";
        case V:
            return "V";
        case X:
            return "X";
        case L:
            return "L";
        case C:
            return "C";
        case D:
            return "D";
        case M:
            return "M";
        default:
            return NULL;
        }
    }
    
    std::string to_roman(const int value) {
        roman_digits weight[] = { I, V, X, L, C, D, M };
        std::string result;
        int t;
        int i;
    
        if (value == 0) {
            return NULL;
        } else {
            unsigned int i;
            for (i = 0; i < sizeof(weight) / sizeof(roman_digits); ++i) {
                if (value == weight[i]) {
                    return lookup(weight[i]);
                }
            }
        }
        i = 0;
        t = value;
        while (t > 0) {
            t = value;
            t /= weight[i++];
        }
        --i;
        int prev_wt_sub = i % 2 ? (i - 1) : (i - 2);
        if ((weight[i] - weight[prev_wt_sub]) < value) {
            result += lookup(weight[prev_wt_sub]) + lookup(weight[i]) +
                    to_roman(value - (weight[i] - weight[prev_wt_sub]));
        } else if ((weight[i] - weight[prev_wt_sub]) > value) {
            prev_wt_sub += (value / weight[prev_wt_sub + 1] ? 1 : 0);
            result += lookup(weight[prev_wt_sub]) +
                    to_roman(value - weight[prev_wt_sub]);
        } else {
            result += lookup(weight[prev_wt_sub]) + lookup(weight[i]);
        }
    
        return result;
    }
    

提交回复
热议问题