Add slow solution to romanToInt
This commit is contained in:
parent
4cd0263710
commit
3caa17b54b
3 changed files with 55 additions and 0 deletions
11
cediackermann/challenges/romanToInt/BUILD
Normal file
11
cediackermann/challenges/romanToInt/BUILD
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
load("@rules_java//java:defs.bzl", "java_binary")
|
||||||
|
|
||||||
|
package(default_visibility = ["//visibility:public"])
|
||||||
|
|
||||||
|
java_binary(
|
||||||
|
name = "romanToInt",
|
||||||
|
main_class = "cediackermann.challenges.houseRobber.Main",
|
||||||
|
srcs = glob(["*.java"]),
|
||||||
|
deps = [
|
||||||
|
],
|
||||||
|
)
|
||||||
11
cediackermann/challenges/romanToInt/Main.java
Normal file
11
cediackermann/challenges/romanToInt/Main.java
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
package cediackermann.challenges.romanToInt;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Solution sol = new Solution();
|
||||||
|
System.out.println(
|
||||||
|
sol.romanToInt("MCMXCIV")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
33
cediackermann/challenges/romanToInt/Solution.java
Normal file
33
cediackermann/challenges/romanToInt/Solution.java
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
package cediackermann.challenges.romanToInt;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
private final Map<String, Integer> romanLetters = new HashMap<>();
|
||||||
|
public Solution(){
|
||||||
|
romanLetters.put("I", 1);
|
||||||
|
romanLetters.put("V", 5);
|
||||||
|
romanLetters.put("X", 10);
|
||||||
|
romanLetters.put("L", 50);
|
||||||
|
romanLetters.put("C", 100);
|
||||||
|
romanLetters.put("D", 500);
|
||||||
|
romanLetters.put("M", 1000);
|
||||||
|
}
|
||||||
|
public int romanToInt(String s) {
|
||||||
|
int solution = 0;
|
||||||
|
for (int i = 0; i < s.length(); i++) {
|
||||||
|
if (i + 1 <= s.length() - 1) {
|
||||||
|
if (this.romanLetters.get(Character.toString(s.charAt(i))) < this.romanLetters.get(Character.toString(s.charAt(i + 1)))) {
|
||||||
|
solution += this.romanLetters.get(Character.toString(s.charAt(i+1))) - this.romanLetters.get(Character.toString(s.charAt(i)));
|
||||||
|
i++;
|
||||||
|
} else{
|
||||||
|
solution += this.romanLetters.get(Character.toString(s.charAt(i)));
|
||||||
|
}
|
||||||
|
} else{
|
||||||
|
solution += this.romanLetters.get(Character.toString(s.charAt(i)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return solution;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue