LeetCode题解-12-Integer to Roman
来源:互联网 发布:阿里云域名几级 编辑:程序博客网 时间:2024/06/06 19:46
解题思路
题意是说把1~3999之间的数字转成罗马数字。
首先要理解罗马数字的表示法,它是按大小结合顺序来的,前面几个字母组合起来如果能够解释成较大的数字,那就使用这个表示,而不是按举个字母来的。
所以数字转成罗马数字,就可以从字母可以表示的最大数字开始,每找到一个就是增加对应的罗马数字,并记录对剩余部分数字匹配,直到这个罗马数字过大,再取一个较小的继续尝试。
参考源码
public class Solution { private static String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private static int[] ints = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; public String intToRoman(int num) { int pos = 0; StringBuilder sb = new StringBuilder(); while (num != 0) { if (num >= ints[pos]) { num -= ints[pos]; sb.append(romans[pos]); } else { pos++; } } return sb.toString(); }}
0 0
- LeetCode 12 Integer to Roman题解
- LeetCode题解-12-Integer to Roman
- LeetCode题解:Roman to Integer
- LeetCode题解:Integer to Roman
- LeetCode题解:Roman to Integer
- LeetCode题解:Integer to Roman
- 《LeetBook》leetcode题解(12):Integer to Roman[M]
- LeetCode 题解(58): Integer to Roman
- LeetCode 题解(73): Roman to Integer
- leetcode题解||Integer to Roman问题
- leetcode题解 || Roman to Integer问题
- LeetCode题解——Roman to Integer
- LeetCode题解——Integer to Roman
- LeetCode题解-13-Roman to Integer
- 12. Integer to Roman LeetCode题解
- 13. Roman to Integer LeetCode题解
- leetcode题解-12. Integer to Roman
- leetcode题解-13. Roman to Integer
- Ubuntu16.04编译Caffe遇到的问题及解决办法
- for循环与setTimeout
- 1127. ZigZagging on a Tree (30)
- JavaScript 数据类型(值类型/引用类型)
- 定义动态数组
- LeetCode题解-12-Integer to Roman
- LeetCode 2 Add Two Numbers
- Socket类的getInputStream方法与getOutputStream方法的使用
- java如何使用反射调用类中的方法
- 第33天(就业班) 关联映射、集合映射、一对多映射、inverse属性、cascade级联操作、多对多映射配置
- java-volatile详解
- LeetCode题解-13-Roman to Integer
- 一道关于最小生成树的傻逼题
- 进程和线程关系及区别