12. Integer to Roman

来源:互联网 发布:电脑提示激活windows 编辑:程序博客网 时间:2024/06/06 05:44
class Solution {
public:
void setDigit(string &res, int n, char x, char y, char z) {
         if (n < 4) {
            for (int i = 0; i < n; ++i) {
               res.push_back(x);
            }
        }
        if (n == 4) {
           res.push_back(x); 
           res.push_back(y);
       }
       if (n == 5) res.push_back(y);
       if (n > 5 && n < 9) {
           res.push_back(y);
           for (int i = 5; i < n; ++i) {
               res.push_back(x);
         }
     }
        if (n == 9) {
           res.push_back(x);
            res.push_back(z);
        }
    }
    string intToRoman(int num) {
         int t = (num / 1000) % 10, h = (num / 100) % 10, d = (num / 10) % 10, n = num % 10;
      string res;
      setDigit(res, t, 'M', '?', '?');
        setDigit(res, h, 'C', 'D', 'M');
       setDigit(res, d, 'X', 'L', 'C');
        setDigit(res, n, 'I', 'V', 'X');
        return res;
    }
};
0 0
原创粉丝点击