Question:
My code:
public class Solution {
public String intToRoman(int num) {
if (num <= 0 || num > 3999)
return null;
String result = "";
int numM = num / 1000;
for (int i = 0; i < numM; i++)
result += 'M';
num = num - (num / 1000) * 1000;
//100-999
int numD = 0;
int numC = 0;
if (num >= 900) {
num = num - 900;
result += "CM";
}
else if (num >= 500){
numD = num / 500;
num = num - (num / 500) * 500;
numC = num / 100;
num = num - (num / 100) * 100;
for (int i = 0; i < numD; i++)
result += 'D';
for (int i = 0; i < numC; i++)
result += 'C';
}
else if (num >= 400) {
num = num - 400;
result += "CD";
}
else {
numC = num / 100;
num = num - (num / 100) * 100;
for (int i = 0; i < numC; i++)
result += 'C';
}
//10-99
int numL = 0;
int numX = 0;
if (num >= 90) {
num = num - 90;
result += "XC";
}
else if (num >= 50) {
numL = num / 50;
num = num - (num / 50) * 50;
numX = num / 10;
num = num - (num / 10) * 10;
for (int i = 0; i < numL; i++)
result += 'L';
for (int i = 0; i < numX; i++)
result += 'X';
}
else if (num >= 40) {
num = num - 40;
result += "XL";
}
else {
numX = num / 10;
num = num - (num / 10) * 10;
for (int i = 0; i < numX; i++)
result += 'X';
}
//1-9
int numV = 0;
int numI = 0;
if (num >= 9) {
num = num - 9;
result += "IX";
}
else if (num >= 5){
numV = num / 5;
num = num - (num / 5) * 5;
numI = num;
for (int i = 0; i < numV; i++)
result += 'V';
for (int i = 0; i < numI; i++)
result += 'I';
}
else if (num >= 4) {
num = num - 4;
result += "IV";
}
else {
numI = num;
for (int i = 0; i < numI; i++)
result += 'I';
}
return result;
}
public static void main(String[] args) {
Solution test = new Solution();
int a = 2014;
System.out.println(test.intToRoman(a));
}
}
My test result:
这次题目没有什么意思。就是得先去理解下罗马数字的规则。然后写一些if语句就行。
主要的情况是,只要那么几个标识符。
比如一个数在100-999之间。
那么就得分情况。
如果 >= 900, 那么百位上的数就可以用 CM来表示
如果 >= 500, 那就是DCCC.....
如果 >= 400, 那就是CD....
其他, 那就是CCC.....
这样之后就可以得到 两位数, XX
然后同样按照 90,50,40,其他的情况来区分。。
以此类推。。。
附带一个罗马数字表和命名准则
http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
https://en.wikipedia.org/wiki/Roman_numerals
**
总结:没多大意思。没有昨天那道水桶题那么带劲,性感!
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public String intToRoman(int num) {
if (num <= 0) {
return null;
}
int[] values = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] strs = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (num >= values[i]) {
sb.append(strs[i]);
num -= values[i];
}
}
return sb.toString();
}
}
reference:
https://discuss.leetcode.com/topic/20510/my-java-solution-easy-to-understand
直接看的答案给的最优解,记住就行。
Anyway, Good luck, Richardo! -- 09/17/2016