12. Integer to Roman
来源:互联网 发布:winpe装linux 编辑:程序博客网 时间:2024/06/16 10:35
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
问题描述:给定一个整数,将其装换成罗马数字(整数转罗马数字)。和 13. Roman to Integer(罗马转数字)相反。
分析:基本罗马数字:I(1)、V(5)、X (10)、L(50)、C(100)、 D(500) 、M(1000),同时还可得到基本型IV(4)、IX(9)、XL(40)、XC(90)、CD(400)、CM(900),其他整数均可由这13个基本型组合得到。
将罗马数字和对应的整数降序分别存入两个数组,为罗马数字数组(romans)、整数数组(numbes),numbers数组中i位置整数转换后对应romans数组中i位置的罗马数字,result记录转换的罗马数字字符串。若整数大于等于整数数组中的值,则将该整数数组中整数对应的罗马数字加入result,同时在num中减去该整数,即每次取满足条件num>=numbers[i]对应的罗马数字。
public class Solution { public String intToRoman(int num) { String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int [] numbers = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; String result = ""; int i = 0; while(num != 0){ if(num >= numbers[i]){ result += romans[i]; num -= numbers[i]; }else{ i++; } } return result; }}
阅读全文
0 0
- 12.Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- nginx
- jsp自定义标签(时间格式化包括Long转时间)
- laravel的 容器container(ioc)
- A1036
- 稳定排序
- 12. Integer to Roman
- redis集群命令
- hadoop2.x入门:编写mapreduce对气象数据集求每日最高气温和最低气温
- Android—(通知、闹钟)
- 音译 —— 本身的含义
- MongoDB学习
- LeetCode 371. Sum of Two Integers
- Return of the Nim
- JS交互