LeetCode 12 Integer to Roman (Integer to Rome)
Translation
Given an integer value, convert it to a Roman number. The input value must be between 1 and 3999.
Original
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
I won't tell you how many variables and If ......
After that, I could not stand so many variables and wrote them as enumeration. Then I would be able to solve them.
To help you understand how Rome counts, I have taken a picture here. You can use Microsoft Bing Search.
Then I posted the code first:
public class Solution{ public string IntToRoman(int num) { string result = ; Type R = typeof(Roman); foreach (var r in Enum.GetNames(R).Reverse()) { while (num >= int.Parse(Enum.Format(R, Enum.Parse(R, r), d))) { result += r.ToString(); num -= int.Parse(Enum.Format(R, Enum.Parse(R, r), d)); } } return result; }}public enum Roman{ 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};
Later today, I will post some usage of C # enumeration to my blog. If you do not know about it, please stay tuned.
In addition to the enumeration usage, I think you need to carefully understand the rules of the number of Rome in this question, that is, remember to add the numbers 9 and 4 to the enumeration.
In IntToRoman What are they all doing?
Matching Type And Typeof New R
Use Foreach Traverse all elements in the enumeration
Remember to add Reverse () As for the reason, you will find out if you try not to add it.
If Num If the value is greater than the number in the enumeration, add the corresponding string (for example, "M") Result Medium
Finally Num To remove the number that has been used. The number is also obtained through enumeration.
Last return Result
Now, we are ready to meet the next question.
The next question is about the number of Rome, but it is converted from the number of Rome to an Integer. Welcome to visit: LeetCode 13 Roman to Integer (the number of Rome to an Integer ).