您的位置:首页 > 其它

leetcode - 12.Integer to Roman

2017-03-02 19:46 411 查看

Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Solution1:

public String intToRoman(int num) {
String[] strs = new String[] { "I", "V", "X", "L", "C", "D", "M" };
int _num;
String result = "";
int i = 0;

while (num > 0) {
_num = num % 10;

switch (_num) {
case 0:
break;
case 1:
result = strs[i] + result;
break;
case 2:
result = strs[i] + strs[i] + result;
break;
case 3:
result = strs[i] + strs[i] + strs[i] + result;
break;
case 4:
result = strs[i] + strs[i + 1] + result;
break;
case 5:
result = strs[i + 1] + result;
break;
case 6:
result = strs[i + 1] + strs[i] + result;
break;
case 7:
result = strs[i + 1] + strs[i] + strs[i] + result;
break;
case 8:
result = strs[i + 1] + strs[i] + strs[i] + strs[i] + result;
break;
case 9:
result = strs[i] + strs[i + 2] + result;
break;
}

num /= 10;
i += 2;

}

return result;
}


Solution2:

better

public String intToRoman(int num) {
String[] I = new String[] { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
String[] X = new String[] { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
String[] C = new String[] { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
String[] M = new String[] { "", "M", "MM", "MMM" };

return M[num / 1000] + C[num / 100 % 10] + X[num / 10 % 10] + I[num % 10];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode