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:
這次題目沒有什么意思丝蹭。就是得先去理解下羅馬數(shù)字的規(guī)則氢卡。然后寫一些if語句就行惨撇。
主要的情況是虐秦,只要那么幾個(gè)標(biāo)識符。
比如一個(gè)數(shù)在100-999之間碗短。
那么就得分情況。
如果 >= 900, 那么百位上的數(shù)就可以用 CM來表示
如果 >= 500, 那就是DCCC.....
如果 >= 400, 那就是CD....
其他题涨, 那就是CCC.....
這樣之后就可以得到 兩位數(shù)偎谁, XX
然后同樣按照 90,50,40,其他的情況來區(qū)分纲堵。巡雨。
以此類推。席函。铐望。
附帶一個(gè)羅馬數(shù)字表和命名準(zhǔn)則
http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
https://en.wikipedia.org/wiki/Roman_numerals
**
總結(jié):沒多大意思。沒有昨天那道水桶題那么帶勁茂附,性感正蛙!
**
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
直接看的答案給的最優(yōu)解,記住就行营曼。
Anyway, Good luck, Richardo! -- 09/17/2016