• 문제 링크
Integer to Roman - LeetCode
Can you solve this real interview question? Integer to Roman - Seven different symbols represent Roman numerals with the following values: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Roman numerals are formed by appending the conversions of decimal
leetcode.com
• 풀이 코드
public class Solution {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
repeat('M', num / 1000, sb);
num %= 1000;
measure('C', 'D', 'M', num / 100, sb);
num %= 100;
measure('X', 'L', 'C', num / 10, sb);
num %= 10;
measure('I', 'V', 'X', num, sb);
return sb.toString();
}
private void measure(char cur, char mid, char next, int i, StringBuilder sb) {
if (i == 0) return;
if (i < 4) repeat(cur, i, sb);
else if (i == 4) sb.append(cur).append(mid);
else if (i < 9) repeat(cur, i - 5, sb.append(mid));
else sb.append(cur).append(next);
}
private void repeat(char c, int i, StringBuilder sb) {
while (i-- > 0) sb.append(c);
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 14. Longest Common Prefix - Java (0) | 2026.05.11 |
|---|---|
| [LeetCode] 13. Roman to Integer - Java (0) | 2026.05.10 |
| [LeetCode] 11. Container With Most Water - Java (0) | 2026.05.08 |
| [LeetCode] 9. Palindrome Number - Java (0) | 2026.05.07 |
| [LeetCode] 3. Longest Substring Without Repeating Characters - Java (0) | 2026.05.06 |
댓글