Share my special solution


  • 0
    X
    class Solution {
    public:
        string intToRoman(int num) {
            char symbol[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
            int i = sizeof(symbol)/sizeof(symbol[0]) - 1;
            string result;
            while (num) {
                    const int w = weight(i);
                    while (num >= w) { // handle 1,2,3 ,5,6,7,8 ...
                            result.append(1, symbol[i]);
                            num -= w;
                    }
    
                    if (i) {
                            const int one = i - (i+1)%2 - 1;
                            const int w4 = w - weight(one);
                            if (num >= w4) { // handle 4, 9 ...
                                    result.append(1, symbol[one]);
                                    result.append(1, symbol[i]);
                                    num -= w4;
                            }
                            i--;
                    }
            }
            return result;
        }
    
        inline int weight(int i) {
            return pow(5, i%2) * pow(10, i/2);
        }
    
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.