Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
The integers are represented by Roman numerals.
Thinking Analysis:
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
First, starting from the input integer, (1) Take the numeric value on its single digit, and then decide to get a string (the string should also be at the far right of the Roman numeral, so use a stack to solve)
(2) then divide the integer by 10 (the number on the 10-bit), then go to Execution (1)
The code is as follows:
1#include <stack>2 classSolution {3 Public:4 stringInttoroman (intnum) {5vector<vector<string>> Data={6{"","I","II","III","IV","V","VI","VII","VIII","IX"},7{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},8{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},9{"","M","MM","MMM"}Ten }; Onestack<string>STA; A intI=0; - stringres="", result=""; - while(num!=0){ the intremain=num%Ten; -res=Data[i][remain]; - Sta.push (res); -++i; +Num/=Ten; - } + while(!Sta.empty ()) { Aresult+=sta.top (); at Sta.pop (); - } - returnresult; - } -};
Integer to Roman Leetcode C + + implementation