Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0ac2e0a

Browse files
committed
Addd Roman to Integer 🆑
1 parent d70a34a commit 0ac2e0a

File tree

1 file changed

+27
-17
lines changed

1 file changed

+27
-17
lines changed
Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,41 @@
11
package com.anas.easy;
2-
32
public class RomanToInteger {
43
public int romanToInt(String s) {
54
int num = 0;
65
s = s.toLowerCase();
76
for (int i = 0; i < s.length(); i++) {
8-
switch (s.charAt(i)) {
9-
case 'i' -> num++;
10-
case 'v' -> num += v(s, i);
11-
case 'x' -> num += x(s, i);
12-
case 'l' -> num += 50;
13-
case 'c' -> num += 100;
14-
case 'd' -> num += 500;
15-
case 'm' -> num += 1000;
16-
}
7+
num += getNum(s, i);
178
}
189
return num;
1910
}
2011

21-
private int x(String s, int i) {
22-
if (i != 0 && s.charAt(i) ==)
12+
private int getNum(String s, int i) {
13+
int returnVal = getIntNum(s.charAt(i));
14+
if (i != 0) {
15+
short currenNum = (short) returnVal;
16+
short prevNum = getIntNum(s.charAt(i - 1));
17+
if (currenNum > prevNum) {
18+
returnVal = 0;
19+
returnVal -= prevNum;
20+
returnVal += (currenNum - prevNum);
21+
}
22+
}
23+
return returnVal;
24+
}
25+
26+
private short getIntNum(char charAt) {
27+
return switch (charAt) {
28+
case 'v' -> 5;
29+
case 'x' -> 10;
30+
case 'l' -> 50;
31+
case 'c' -> 100;
32+
case 'd' -> 500;
33+
case 'm' -> 1000;
34+
default -> 1;
35+
};
2336
}
2437

25-
private int v(String s, int i) {
26-
if (i != 0 && s.charAt(i - 1) == 'i')
27-
return 4;
28-
else
29-
return 5;
38+
public static void main(String[] args) {
39+
System.out.println("MCMXCIV = " + new RomanToInteger().romanToInt("MCMXCIV") );
3040
}
3141
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /