leetcode-012-Integer to Roman
2016-10-03 22:25
288 查看
P012 Integer to Roman
思路分析
代码
java
Input is guaranteed to be within the range from 1 to 3999.
关键就是找出构成数字的元数字:
二进制的元数字是0和1
十进制的元数字是0到9
罗马数字的元数字如下:
将输入数字按照这种方式拆分成几个千几个百……即可。
思路分析
代码
java
P012 Integer to Roman
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
思路分析
这个和小学数学的考题类似了,比如问123是由几个100,几个10和几个1构成的?关键就是找出构成数字的元数字:
二进制的元数字是0和1
十进制的元数字是0到9
罗马数字的元数字如下:
罗马字符 | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
阿拉伯数字 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
代码
java
public class Solution012 { public static final String[][] base = { // { "", "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" } // }; public String intToRoman(int num) { StringBuilder sb = new StringBuilder(); sb.append(base[3][(num / 1000) % 10]); sb.append(base[2][(num / 100) % 10]); sb.append(base[1][(num / 10) % 10]); sb.append(base[0][(num % 10)]); return sb.toString(); } public static void main(String[] args) { Solution012 s12 = new Solution012(); int xs[] = { 1, 4, 6, 7, 9, 18, 19, 99, 3999 }; for (int x : xs) { System.out.println(x + "-->" + s12.intToRoman(x)); } } }
相关文章推荐
- [LeetCode]-012-Integer to Roman
- leetcode 012 —— Integer to Roman
- 2017-09-09 LeetCode_012 Integer to Roman
- leetcode-012:Integer to Roman
- 【JAVA、C++】LeetCode 012 Integer to Roman
- leetcode解题方案--012--Integer to Roman
- LeetCode 012 Integer to Roman
- LeetCode 012: Integer to Roman
- [LeetCode]题解(python):012-Integer to Roman
- leetcode012:Integer to Roman
- 【LeetCode-面试算法经典-Java实现】【012-Integer to Roman(数字转罗马字符)】
- leetcode012 Integer to Roman
- LeetCode 012 Integer to Roman
- Leetcode012 Integer to Roman
- leetcode_c++: Integer to Roman(012)
- LeetCode 012 Integer to Roman
- leetcode 012 Integer to Roman
- [LeetCode]012-Integer to Roman
- LeetCode 012 Integer to Roman
- LeetCode 012 Integer to Roman