Topic
Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Analysis
This topic requires converting an integer number between a given 1~3999 to a Roman number and outputting it.
To solve this problem, we must understand the correspondence between the Roman alphabet and the integers:
Examples of comparisons are as follows:
AC Code
class solution { Public: String Inttoroman (intNUM) {//Store Roman numeralsStringStr;if(num = =0)return "";//(1) first to handle the highest number of thousand digits if(Num >= +) {int Count= num/ +; for(inti =0; I <Count; i++)Str+ = Romanleter ( +);//Get hundreds ofNum%= +;//Link the remaining three digits corresponding to the Roman sequence Str+ = Inttoroman (num); }//else If Else if(Num >= -) {if(Num >= the) {Str=Str+ Romanleter ( -) + Romanleter ( +); Num%= -; }//if Else if(Num >= -) {Str+ = Romanleter ( -); num-= -; }//else If Else if(Num >= -){Str=Str+ Romanleter ( -) + Romanleter ( -); num-= -; }Else{ while(Num >= -) {Str+ = Romanleter ( -); num-= -; }//while}Str+ = Inttoroman (num); }//else If Else if(Num >=Ten) {if(Num >= -) {Str=Str+ Romanleter (Ten) + Romanleter ( -); Num%=Ten; }//if Else if(Num >= -) {Str+ = Romanleter ( -); num-= -; }Else if(Num >= +){Str=Str+ Romanleter (Ten) + Romanleter ( -); num-= +; }Else{ while(Num >=Ten) {Str+ = Romanleter (Ten); num-=Ten; } }Str+ = Inttoroman (num); }Else if(Num >=1) {if(num = =9) {Str=Str+ Romanleter (1) + Romanleter (Ten); Num/=Ten; }Else if(Num >=5) {Str+ = Romanleter (5); num-=5; }Else if(Num >=4){Str=Str+ Romanleter (1) + Romanleter (5); num-=4; }Else{ while(Num >=1) {Str+ = Romanleter (1); num-=1; } }Str+ = Inttoroman (num); }Else Str+=" the";return Str; } String Romanleter (intN) {Switch(n) { Case 1:return "I"; Break; Case 5:return "V"; Break; Case Ten:return "X"; Break; Case -:return "L"; Break; Case -:return "C"; Break; Case -:return "D"; Break; Case +:return "M"; Break;default:return ""; Break; } }};
GIT test program code
Leetcode () Integer to Roman