Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-10-20 17:21:06
12. Integer to Roman
给予一个1到3999之间的整数,将这个整数转成罗马符号表示法,罗马数字是以拼接的方
方式表示,例如:
I = 1
II = 2
III = 3
但是遇到四个连续符号时会经过转换,例如:
IIII != 4
要改成大数在右,而小数在左:
IX = 5-1 = 4
(从左边读到右边时,如果有小数在左表示是右数减左数)
X = 5
XI = 6
XII = 7
XIII = 8
IX = 9
X = 10
.....
所以会变成一个{1, 4, 5, 9, 10 ,40, ...} 的循环
Example:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
思路:
1.建立一个所有罗马数字表示的表。
I 1
IV 4
V 5
XI 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000
2.从数字大到小,如果可以用大数表示就把特定字串append,并减去该数字,直到不
能用大数表示时再去找小的,直到数字用完为止。
JavaCode:
class Solution {
public static String intToRoman(int num){
StringBuilder result = new StringBuilder();
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"};
int[] values = {1000, 900, 500, 400, 100, 90, 50,
40, 10, 9, 5, 4, 1 };
int i = 0;
while (num > 0) {
while ( num >= values[i]) {
num -= values[i];
result.append(roman[i]);
}
i++;
}
return result.toString();
}
}
罗马爹压噜
作者: sustainer123 (caster)   2022-10-20 17:22:00
大师
作者: Jaka (Jaka)   2022-10-20 17:41:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com