Integer to Roman
来源:互联网 发布:c语言的视频教程 编辑:程序博客网 时间:2024/05/10 04:58
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字有如下符号:
基本字符IVXLCDM对应阿拉伯数字1510501005001000
计数规则:
- 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
- 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
- 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
- 正常使用时,连续的数字重复不得超过三次
- 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规
思路 1 : 从后往前遍历, 遇到一样的就粘贴上。 i = i + 2; num = num / 10;
思路2 : 只有4,9是左减,其余的数字都是右加。所以,构建两个数组,分别是数字和对应的字母。数字,要把所有的4,9加进来。包括4,9,40,90,400,900. 从前往后, 用取余的方法 来进位 ,num %= base[i];
public class Solution { public String intToRoman(int num) { if(num <= 0 || num >= 4000) return null; String roman[] = { "I","V","X","L","C","D","M" }; String RomanString = ""; int i = 0; while(num != 0) { int temp = num % 10; String Rstr = ""; switch(temp) { case 1: Rstr = roman[i]; break; case 2: Rstr = roman[i] + roman[i]; break; case 3: Rstr = roman[i] + roman[i] + roman[i]; break; case 4: Rstr = roman[i] + roman[i+1]; break; case 5: Rstr = roman[i+1]; break; case 6: Rstr = roman[i+1] + roman[i]; break; case 7: Rstr = roman[i+1] + roman[i] + roman[i]; break; case 8: Rstr = roman[i+1] + roman[i] + roman[i] + roman[i]; break; case 9: Rstr = roman[i] + roman[i+2]; break; } RomanString = Rstr + RomanString; i = i + 2; num = num / 10; } return RomanString; }}
public class Solution { public String intToRoman(int num) { int[] base = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };String[] roman = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X","IX", "V", "IV", "I" };String result = "";for (int i = 0; num > 0; i++) {int count = num / base[i];num %= base[i];while (count > 0) {result += roman[i];--count;}}return result; }}
0 0
- Integer to Roman & Roman to Integer
- Integer to Roman & Roman to Integer
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- Mac下搭建服务器
- xcode6中viewwithtag取不到值,返回nil。解决方案
- HTML5实现摇一摇的功能(实测后)
- 新浪UED:教你快速制作Icon Font
- Ubuntu, phpmyadmin,缺少mcrypt 扩展(不同的情况)
- Integer to Roman
- Titanium中创建android module(一):环境配置
- HTML5三种对密码加密的方法
- 1501101124-蓝桥杯-算法训练 Anagrams问题
- 海尔去年营收2千亿,LG比格力多2千亿!
- 计算机视觉领域的一些牛人博客,超有实力的研究机构等的网站链接
- Visual studio 2013 快捷键 还原 visual studio 2010
- html对象中内容过长的处理方法
- [网络编程] 邮箱协议 SMPT 使用心得