Integer to Roman--LeetCode

来源:互联网 发布:新网域名转出到阿里云 编辑:程序博客网 时间:2024/06/06 20:39

1.题目

Integer to Roman

2.代码

class Solution {public:    string intToRoman(int num) {        string res = "";        char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};        int value[] = {1000, 500, 100, 50, 10, 5, 1};        for (int n = 0; n < 7; n += 2)         {            int x = num / value[n];            if (x < 4)             {                for (int i = 1; i <= x; ++i)                     res += roman[n];            }             else if (x == 4)             {                res = res + roman[n] + roman[n - 1];            }            else if (x > 4 && x < 9)             {                res += roman[n - 1];                for (int i = 6; i <= x; ++i)                     res += roman[n];            }            else if (x == 9)             {                res = res + roman[n] + roman[n - 2];            }            num %= value[n];                    }        return res;    }};
原创粉丝点击