Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from
Have you met this question in a real interview? 1
to 3999
.
Yes
Example
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
more examples at:http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
Clarification
What is Roman Numeral?
- https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- http://baike.baidu.com/view/42061.htm
public class Solution {
/**
* @param n The integer
* @return Roman representation
*/
public String intToRoman(int n) {
// Write your code here
String[] symbols = {"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};
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < values.length; i++){
while(n >= values[i]){
buffer.append(symbols[i]);
n -= values[i];
}
}
return buffer.toString();
}
}
No comments:
Post a Comment