Integer to Roman
Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Do the processing by interval.
Solution One: Non-recursive
classSolution { Public: stringInttoroman (intnum) { stringret; //m<-->1000 while(Num >= +) {ret+='M'; Num-= +; } //to here, num <//cm<-->900 if(Num >= the) {ret+="CM"; Num-= the; } //to here, num <//d<-->500 if(Num >= -) {ret+='D'; Num-= -; } //to here, num < if(Num >= -) {ret+="CD"; Num-= -; } //to here, num <//c<-->100 while(Num >= -) {ret+='C'; Num-= -; } //to here, num <//xc<-->90 if(Num >= -) {ret+="XC"; Num-= -; } //to here, num <//l<-->50 if(Num >= -) {ret+='L'; Num-= -; } //to here, num <//xl<-->40 if(Num >= +) {ret+="XL"; Num-= +; } //to here, num <//x<-->10 while(Num >=Ten) {ret+='X'; Num-=Ten; } //to here, num <//ix<-->9 if(Num >=9) {ret+="IX"; Num-=9; } //to here, num < 9//v<-->5 if(Num >=5) {ret+='V'; Num-=5; } //to here, num < 5//iv<-->4 if(Num >=4) {ret+="IV"; Num-=4; } //to here, num < 4//i<-->1 while(Num >=1) {ret+='I'; Num-=1; } returnret; }};
Solution Two: Recursion
classSolution { Public: stringInttoroman (intnum) { if(num>= +) return "M"+inttoroman (num- +); Else if(num>= the) return "CM"+inttoroman (num- the); Else if(num>= -) return "D"+inttoroman (num- -); Else if(num>= -) return "CD"+inttoroman (num- -); Else if(num>= -) return "C"+inttoroman (num- -); Else if(num>= -) return "XC"+inttoroman (num- -); Else if(num>= -) return "L"+inttoroman (num- -); Else if(num>= +) return "XL"+inttoroman (num- +); Else if(num>=Ten) return "X"+inttoroman (num-Ten); Else if(num>=9) return "IX"+inttoroman (num-9); Else if(num>=5) return "V"+inttoroman (num-5); Else if(num>=4) return "IV"+inttoroman (num-4); Else if(num>=1) return "I"+inttoroman (num-1); Else return ""; }};
"Leetcode" Integer to Roman (2 solutions)