A straight forward translate solution


  • 2
    S
    // the Roman seven symbols:
    // I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
    // the Roman rules:
    // the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
    // X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
    // C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern
    string intToRoman(int num) {
        string ans;    
        if (num >= 1000) { ans.append(num/1000, 'M'); num %= 1000; }
        if (num >= 900) { ans += "CM"; num -= 900; }
        if (num >= 500) { ans.append(1, 'D'); num -= 500; }
        if (num >= 400) { ans += "CD"; num -= 400; }
        if (num >= 100) { ans.append(num/100, 'C'); num %= 100; }
        if (num >= 90) { ans += "XC"; num -= 90; }
        if (num >= 50) { ans.append(1, 'L'); num -= 50; }
        if (num >= 40) { ans += "XL"; num -= 40; }
        if (num >= 10) { ans.append(num/10, 'X'); num %= 10; }
        if (num >= 9) { ans += "IX"; num -= 9; }
        if (num >= 5) { ans.append(1, 'V'); num -= 5; }
        if (num >= 4) { ans += "IV"; num -= 4; }
        if (num >= 1) { ans.append(num/1, 'I'); num = 0; }
        return ans;
    }

Log in to reply
 

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