leetcode - roman to integer & integer to roman

个人认为这两道题目从算法设计上来说都非常简单,主要是要弄懂roman和integer互相转换的规则。
那么首先我们来看看规则,规则如下:
I:1 V:5 X:10 L:50 C:100 D:500 M:1000
基本规则:
(1)左边的数大于等于右边的数字,表示数字相加
(2)小的数字(闲鱼I、X和C)写在大的数字左边,得到的数应该是大数减小数
(3)一个数字上面加上横线,表示这个数增至1000
组数规则:
(1)I、X、C中任何一个,自身连用或者放在大数右边,不可以超过三个;放在大数左边,只能用一个;
(2)不能把V、L、D中任何一个作为小数放在大数左边,放在大数的右边只能使用一个;
(3)V和X左边的小数只能是I;
(4)L和C左边的小数只能是X;
(5)D和M左边的小数只能用C;
Problem1: Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:

public class Solution { public int romanToInt(String s) { char[] romanarray = s.toCharArray(); int addnum = getonechar(romanarray[0]); int temp = addnum; //将罗马数一个个取出,转换成对应的阿拉伯数字 for (int i = 0 ; i < romanarray.length-1 ; i++){ int num = getonechar(romanarray[i+1]); //左边减右边加 if(temp >= num )addnum = addnum + num; else addnum = addnum + num - 2*temp; temp = num; } return addnum; } //罗马数与阿拉伯数映射表 public int getonechar(char s){ switch(s){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; } }

Problem2: Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
【leetcode - roman to integer & integer to roman】Solution:
注意,这里说了不超过3999,其实是简化了问题,不会出现三个连续的阿拉伯数字了。因此可以枚举出来。
这里注意几个细节:
(1)当需要string相add的时候,string必须初始化!
(2)注意,当某位数为0的时候,这个时候如果只是取数组中digit-1的数的时候,会出现outofindex
public class Solution { public String intToRoman(int num) { String[][] roman = { {"I","II","III","IV","V","VI","VII","VIII","IX"}, {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}, {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}, {"M","MM","MMM"} }; int i = 0; String one = ""; while(num != 0){ int digit = num % 10; if(digit != 0){ one = roman[i][digit-1] + one; } i++; num = num/10; }return one; }}

    推荐阅读