Skip to content

Commit

Permalink
Create IntToRoman.java
Browse files Browse the repository at this point in the history
  • Loading branch information
huangsam authored Nov 13, 2024
1 parent 06d64e2 commit 045abc7
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions java/IntToRoman.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// https://leetcode.com/problems/integer-to-roman/

public class IntToRoman {
/**
* Convert integer to Roman numeral. We start by holding
* all the Roman mappings in an array, along with edge cases
* like 900, 400, 90, 40, 9, 4. We then iterate through the
* array and keep subtracting the value from the number until
* we reach 0.
*/
public String intToRoman(int num) {
Roman[] romans = new Roman[] { // Includes 900, 400, 90, 40, 9, 4
new Roman(1000, "M"), new Roman(900, "CM"),
new Roman(500, "D"), new Roman(400, "CD"),
new Roman(100, "C"), new Roman(90, "XC"),
new Roman(50, "L"), new Roman(40, "XL"),
new Roman(10, "X"), new Roman(9, "IX"),
new Roman(5, "V"), new Roman(4, "IV"),
new Roman(1, "I")
};
int pointer = 0;
StringBuilder builder = new StringBuilder();
while (num > 0) {
Roman roman = romans[pointer];
while (num >= roman.value()) {
num -= roman.value();
builder.append(roman.code());
}
pointer++;
}
return builder.toString();
}

private record Roman(int value, String code) {
}
}

0 comments on commit 045abc7

Please sign in to comment.