Given an integer A, convert it to a roman numeral, and return a string corresponding to its roman numeral version
Note : This question has a lot of scope of clarification from the interviewer. Please take a moment to think of all the needed clarifications and see the expected response using “See Expected Output”For the purpose of this question, https://projecteuler.net/about=roman_numerals has very detailed explanations.
Input Format
The only argument given is integer A.
Output Format
Return a string denoting roman numeral version of A.
Constraints
1 <= A <= 3999
For Example
Input 1:
A = 5
Output 1:
"V"
Input 2:
A = 14
Output 2:
"XIV"
Solution:
Time: O(1)
public class Solution {
public String intToRoman(int A) {
StringBuilder sb = new StringBuilder();
while (A >= 1000) {
sb.append('M');
A -= 1000;
}
if (A >= 900) {
sb.append("CM");
A -= 900;
}
if (A >= 500) {
sb.append('D');
A -= 500;
}
if (A >= 400) {
sb.append("CD");
A -= 400;
}
while (A >= 100) {
sb.append('C');
A -= 100;
}
if (A >= 90) {
sb.append("XC");
A -= 90;
}
if (A >= 50) {
sb.append('L');
A -= 50;
}
if (A >= 40) {
sb.append("XL");
A -= 40;
}
while (A >= 10) {
sb.append('X');
A -= 10;
}
if (A >= 9) {
sb.append("IX");
A -= 9;
}
if (A >= 5) {
sb.append('V');
A -= 5;
}
if (A >= 4) {
sb.append("IV");
A -= 4;
}
while (A >= 1) {
sb.append('I');
A -= 1;
}
return sb.toString();
}
}
class Solution {
public String intToRoman(int num) {
if (num < 1 || num > 3999) return "";
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();
}
}