Leetcode-12. Integer to Roman
来源:互联网 发布:信息与数据的区别 编辑:程序博客网 时间:2024/06/08 19:16
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
首先要了解一下罗马数字的规则:
罗马数字共有7个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。按照下面的规则可以表示任意正整数。
重复数次:1个罗马数字重复几次,就表示这个数的几倍。
右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。在一个较大的数字的左边记上1个较小的罗马数字,表示大数字减小数字。但是,左减不能跨越一个位数。比如,99不可以用IC表示,而是用XCIX表示。此外,左减数字不能超过1位,比如8写成VIII,而非IIX。同理,右加数字不能超过3位,比如14写成XIV,而非XIIII。
----------------------分割线----------------------------------
看了一下大家的解法,基本都是用贪心法,但是没有说明原因,为什么取:"M","CM","D","CD","C","L","XL","X","V","IV","I"。其实原因也很简单,因为采用的都是字符串追加小的数,因此需要将左减的情况提出来。Your runtime beats 29.23% of java submissions.
public class Solution { public String intToRoman(int num) { String[] symbols = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};int [] values = new int[] {1000,900,500,400,100,90,50,40,10,9,5,4,1};StringBuffer sb = new StringBuffer("");for(int i = 0; i < values.length; i ++){while(num >= values[i]){sb.append(symbols[i]);num -= values[i];}}return sb.toString(); }}
- LeetCode 12. Integer to Roman
- [LeetCode]12.Integer to Roman
- LeetCode --- 12. Integer to Roman
- [Leetcode] 12. Integer to Roman
- [leetcode] 12.Integer to Roman
- leetcode 12. Integer to Roman
- leetcode 12. Integer to Roman
- [LeetCode]12. Integer to Roman
- leetcode 12. Integer to Roman
- LeetCode *** 12. Integer to Roman
- LeetCode 12. Integer to Roman
- leetcode 12. Integer to Roman
- leetcode 12. Integer to Roman
- Leetcode 12. Integer to Roman
- [Leetcode] 12. Integer to Roman
- leetcode 12. Integer to Roman
- 【leetcode】12. Integer to Roman
- Leetcode-12. Integer to Roman
- Sample之ShaderCamera_Example
- SQL like '%[^0-9]%' 以及{0}的含义
- linux的nohup命令的用法。
- Codeforces Round #366 (Div. 2)
- 欢迎使用CSDN-markdown编辑器
- Leetcode-12. Integer to Roman
- 对话框
- Maven配置本地仓库
- 对话框自带滚动条的使用
- C#编码约定
- union和union all的区别
- Windows Server2003系统安全设置
- 安卓Android studio国际化方法插件安装---快速翻译工具
- yii2框架中(解压包安装的框架),composer安装yiisoft/yii2-jui出现错误,问题解决