Dare2Solve
Roman numerals are formed by appending symbols based on specific rules:
If the value does not start with 4 or 9, symbols are selected from highest to lowest value.
Subtractive forms (e.g., IV for 4, IX for 9) are used for certain combinations.
There are limitations on consecutive use of symbols (e.g., I, X, C, M can appear at most 3 times).
Define Symbols and Values:
Iterative Conversion:
Subtractive Forms:
Return Result:
O(1) since the maximum number of iterations is limited by the number of predefined symbols and their values.
O(1) for the same reason, as the space used does not scale with the size of the input.
This approach ensures that the conversion from an integer to its Roman numeral representation follows the rules provided efficiently and correctly.
class Solution {
public:
string intToRoman(int num) {
map<int, string> values =
{{1,"I"},{4,"IV"},{5,"V"},{9,"IX"},{10,"X"},{40,"XL"},{50,"L"},{90,"XC"},{100,"C"},{400,"CD"},{500,"D"}, {900,"CM"},{1000,"M"}};
string res;
map<int, string>::reverse_iterator it;
for (it = values.rbegin(); it != values.rend(); it++){
while(num>=it->first){
res+=it->second;
num-=it->first;
}
}
return res;
}
};
class Solution:
def intToRoman(self, num: int) -> str:
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
result = []
for i in range(len(values)):
while num >= values[i]:
num -= values[i]
result.append(symbols[i])
return ''.join(result)
class Solution {
public String intToRoman(int num) {
String ones[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
String tens[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
String hrns[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
String ths[] = { "", "M", "MM", "MMM" };
return ths[num / 1000] + hrns[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
}
}
/**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
const romanNum = {
V̆̈: 5000,
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
}
var str = ''
for (var i of Object.keys(romanNum)) {
var q = Math.floor(num / romanNum[i])
num -= q * romanNum[i]
str += i.repeat(q)
}
return str
};