Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
1000~3000: {"M", "MM", "MMM"}.
很常规的题。
public class Solution { public String intToRoman(int num) { String[][] r = { {"", "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"} }; String ans = ""; int i = 0; while (num > 0) { int j = num % 10; ans = r[i][j] + ans; i++; num /= 10; } return ans; } }
public class Solution { int romanToInt(String s) { int ans = change(s.charAt(0)); for (int i = 1; i < s.length(); i++) { if (change(s.charAt(i-1)) < change(s.charAt(i)) ){ ans += change(s.charAt(i)) - 2 * change(s.charAt(i-1)); } else { ans += change(s.charAt(i)); } } return ans; } int change(char ch) { switch (ch) { case ‘I‘: return 1; case ‘V‘: return 5; case ‘X‘: return 10; case ‘L‘: return 50; case ‘C‘: return 100; case ‘D‘: return 500; case ‘M‘: return 1000; } return 0; } }
LeetCode 12-13:Integer to Roman&&Roman to Integer
原文:http://www.cnblogs.com/gonewithgt/p/4571702.html