-
Notifications
You must be signed in to change notification settings - Fork 0
/
romanToInteger.java
54 lines (42 loc) · 1.32 KB
/
romanToInteger.java
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
class romanToInteger {
public int romanToInt(String s) {
// Total value
int sum = 0;
//length of value
int n = s.length(); //LVIII (58) - length 5
for(int i = 0; i < n; i++) {
//current value of the character
int curr = valueOfRomanChar(s.charAt(i));
if (i < n -1) {
//next value of the character
int next = valueOfRomanChar(s.charAt(i + 1));
if (curr >= next) {
sum = sum + curr; //50 5 1 1 1
}
else {
sum = sum + next - curr;
i++;
}
}
else{
sum = sum + curr;
}
}
return sum; //50 55 56 57 58
}
int valueOfRomanChar(char sym){
if (sym == 'I') return 1;
if (sym == 'V') return 5;
if (sym == 'X') return 10;
if (sym == 'L') return 50;
if (sym == 'C') return 100;
if (sym == 'D') return 500;
if (sym == 'M') return 1000;
return 0;
}
public static void main(String args[]){
romanToInteger ob = new romanToInteger();
String str = "LVIII";
System.out.println( ob.romanToInt(str));
}
}