LeetCode-Integer to Roman

1. Integer to Roman (Medium)

Description
Given an integer, convert it to a roman numeral.

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

Analysis
对于个位、十位、百位、千位,数字转换成罗马数字的方法都是一样的,用一个transform函数表示即可。

罗马字符 I   V   X   L   C   D   M
整数数字 1   5   10  50  100 500 1000

代码:

class Solution {
public:
    void transform(string &str, int n, char one, char five, char ten) {
        switch (n) {
            case 1:
                str.push_back(one);
                break;
            case 2:
                str.push_back(one);
                str.push_back(one);
                break;
            case 3:
                str.push_back(one);
                str.push_back(one);
                str.push_back(one);
                break;
            case 4:
                str.push_back(one);
                str.push_back(five);
                break;
            case 5:
                str.push_back(five);
                break;
            case 6:
                str.push_back(five);
                str.push_back(one);
                break;
            case 7:
                str.push_back(five);
                str.push_back(one);
                str.push_back(one);
                break;
            case 8:
                str.push_back(five);
                str.push_back(one);
                str.push_back(one);
                str.push_back(one);
                break;
            case 9:
                str.push_back(one);
                str.push_back(ten);
                break;
            case 0:
                break;
            default:break;
        }
    }

    string intToRoman(int num) {
        string result;
        int temp = num;
        if (temp == 0)
            return result;
        int thousand = temp / 1000;
        temp = temp % 1000;
        int hundred = temp / 100;
        temp = temp % 100;
        int ten = temp / 10;
        temp = temp % 10;
        int one = temp;
        transform(result, thousand, 'M', ' ', ' '); //1000以上的罗马数字字符未知,用空格代替,题目要求只到3999,所以用不到这些字符
        transform(result, hundred, 'C', 'D', 'M');
        transform(result, ten, 'X', 'L', 'C');
        transform(result, one, 'I', 'V', 'X');
        return result;
    }
};
点赞