[leetcode] 12. Integer to Roman
Posted 冬日焰火
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 12. Integer to Roman相关的知识,希望对你有一定的参考价值。
关于罗马数字:
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000
字母可以重复,但不超过三次,当需要超过三次时,用与下一位的组合表示:
I: 1, II: 2, III: 3, IV: 4
C: 100, CC: 200, CCC: 300, CD: 400
提取每一位digit,然后convert to 罗马数字
public class Solution { private static char[][] chars = {{‘I‘, ‘V‘}, {‘X‘, ‘L‘}, {‘C‘, ‘D‘}, {‘M‘, ‘O‘}}; public String intToRoman(int num) { int copy_num = num; int count = 0; StringBuilder result = new StringBuilder(); while (copy_num != 0) { int x = copy_num / 10; int digit = copy_num - x * 10; switch (digit) { case 3: result.append(chars[count][0]); case 2: result.append(chars[count][0]); case 1: result.append(chars[count][0]); case 0: break; case 4: result.append(chars[count][1]); result.append(chars[count][0]); break; case 8: result.append(chars[count][0]); case 7: result.append(chars[count][0]); case 6: result.append(chars[count][0]); case 5: result.append(chars[count][1]); break; case 9: result.append(chars[count + 1][0]); result.append(chars[count][0]); break; } count++; copy_num = x; } result = result.reverse(); return result.toString(); } }
以上是关于[leetcode] 12. Integer to Roman的主要内容,如果未能解决你的问题,请参考以下文章