-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathRomanToNumeral.java
84 lines (76 loc) · 2.24 KB
/
RomanToNumeral.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.interviewbit.string_parsing;
import java.util.HashMap;
import java.util.Map;
/**
* https://www.interviewbit.com/problems/roman-to-integer/
* <p>
* Given a string A representing a roman numeral.
* Convert A into integer.
* <p>
* A is guaranteed to be within the range from 1 to 3999.
* <p>
* NOTE: Read more
* details about roman numerals at Roman Numeric System
* <p>
* <p>
* <p>
* Input Format
* <p>
* The only argument given is string A.
* Output Format
* <p>
* Return an integer which is the integer verison of roman numeral string.
* For Example
* <p>
* Input 1:
* A = "XIV"
* Output 1:
* 14
* <p>
* Input 2:
* A = "XX"
* Output 2:
* 20
*
* @author neeraj on 2019-08-02
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class RomanToNumeral {
final static Map<Character, Integer> romanValue = new HashMap<>();
static {
romanValue.put('I', 1);
romanValue.put('V', 5);
romanValue.put('X', 10);
romanValue.put('L', 50);
romanValue.put('C', 100);
romanValue.put('D', 500);
romanValue.put('M', 1000);
}
public static void main(String[] args) {
System.out.println(romanToInt("XIV"));
System.out.println(romanToInt("XX"));
System.out.println(romanToInt("XVV"));
System.out.println(romanToInt("XV"));
System.out.println(romanToInt("MDCL"));
System.out.println(romanToInt("MMMCCL"));
System.out.println(romanToInt("MMMCCLXIV"));
System.out.println(romanToInt("MMMCCXLIV"));
System.out.println(romanToInt("IX"));
}
public static int romanToInt(String A) {
int result = 0;
int current;
for (int i = 0; i < A.length() - 1; i++) {
current = romanValue.get(A.charAt(i));
// If Next Value is greater than the current, then we have to subtract
if (current < romanValue.get(A.charAt(i + 1))) {
current = -current; // Since this smaller value has to be subtracted
}
result += current;
}
// Since in the above loop we didn't consider last digit, let's include that as well.
result += romanValue.get(A.charAt(A.length() - 1));
return result;
}
}