Integer to Roman
Links: https://leetcode.com/problems/integer-to-roman/
Problem Description:
Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Hide Tags Math String
The problem is to convert Arabic numerals into Roman numerals.
The rules of the Roman numerals have been written here http://blog.csdn.net/efergrehbtrj/article/details/46538711. The simplest thing to do is to take the low-to-high of the numbers. Take one bit at a time, take one and then the number is 10, and the number taken out is expressed in Roman numerals. It is important to note that if the current bit is not the original number, you need to expand 10 times times or 100 times times.
Class Solution {public:string inttoroman (int num) {string result= ""; int n=0; int index=-1; while (num>0) {string S; n=num%10; num/=10; index++; Switch (n) {case 0:break; Case 1:s+= "I"; Case 2:s+= "II"; Case 3:s+= "III"; Case 4:s+= "IV"; Case 5:s+= "V"; Case 6:s+= "VI"; Case 7:s+= "VII"; Case 8:s+= "VIII"; Case 9:s+= "IX"; } for (int k=0;k<index;k++) for (int i=0;i<s.length (); i++) {switch (S[i] {case ' I ': s[i]= ' X '; Case ' V ': s[i]= ' L '; Case ' X ': s[i]= ' C '; Case ' L ': s[i]= ' D '; Case ' C ': s[i]= ' M '; }} Result=s+result; } return result; }};
This is not easy to understand the code and the operation is too cumbersome. Consider the ability to create a table to operate on.
class Solution {public: string intToRoman(int num) { int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; string result=""; string s[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; for (int i = 0; i < 13; i++) { while (num >= values[i]) { num -= values[i]; result+=s[i]; } } return result; }};
12Integer to Roman