-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInteger_to_Roman.java
More file actions
69 lines (61 loc) · 2.21 KB
/
Integer_to_Roman.java
File metadata and controls
69 lines (61 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
12. Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
public class Solution {
public String intToRoman(int num) {
String[] oneLetters = {"I","X","C","M"};
String[] fiveLetters = {"V","L","D",""};
String numStr = num+"";
String output = "";
for(int i=numStr.length()-1; i>=0; i--) {
String tmp = "";
int bit = (int)num%(int)Math.pow(10,i+1)/(int)Math.pow(10,i);
switch (bit){
case 1: tmp = oneLetters[i];
break;
case 2: tmp = oneLetters[i]+oneLetters[i];
break;
case 3: tmp = oneLetters[i]+oneLetters[i]+oneLetters[i];
break;
case 4: tmp = oneLetters[i]+fiveLetters[i];
break;
case 5: tmp = fiveLetters[i];
break;
case 6: tmp = fiveLetters[i]+oneLetters[i];
break;
case 7: tmp = fiveLetters[i]+oneLetters[i]+oneLetters[i];
break;
case 8: tmp = fiveLetters[i]+oneLetters[i]+oneLetters[i]+oneLetters[i];
break;
case 9: tmp = oneLetters[i]+oneLetters[i+1];
break;
default: tmp = "";
break;
}
output += tmp;
}
return output;
}
}
///////////////
//http://bangbingsyb.blogspot.com/2014/11/leetcode-integer-to-roman.html
public class Solution {
public String intToRoman(int num) {
if(num <= 0) {
return "";
}
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder res = new StringBuilder();
int digit=0;
while (num > 0) {
int times = num / nums[digit];
num -= nums[digit] * times;
for ( ; times > 0; times--) {
res.append(symbols[digit]);
}
digit++;
}
return res.toString();
}
}