diff --git a/5.leetcode/src/com/fanxb/common/Q12.java b/5.leetcode/src/com/fanxb/common/Q12.java new file mode 100644 index 0000000..801749a --- /dev/null +++ b/5.leetcode/src/com/fanxb/common/Q12.java @@ -0,0 +1,68 @@ +package com.fanxb.common; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created with IntelliJ IDEA + * + * @author fanxb + * Date: 2020/6/10 10:49 + */ +public class Q12 { + + public String intToRoman(int num) { + StringBuilder stringBuilder = new StringBuilder(); + while (num > 0) { + if (num >= 1000) { + stringBuilder.append("M"); + num -= 1000; + } else if (num >= 900) { + stringBuilder.append("CM"); + num -= 900; + } else if (num >= 500) { + stringBuilder.append("D"); + num -= 500; + } else if (num >= 400) { + stringBuilder.append("CD"); + num -= 400; + } else if (num >= 100) { + stringBuilder.append("C"); + num -= 100; + } else if (num >= 90) { + stringBuilder.append("XC"); + num -= 90; + } else if (num >= 50) { + stringBuilder.append("L"); + num -= 50; + } else if (num >= 40) { + stringBuilder.append("XL"); + num -= 40; + } else if (num >= 10) { + stringBuilder.append("X"); + num -= 10; + } else if (num == 9) { + stringBuilder.append("IX"); + num -= 9; + } else if (num >= 5) { + stringBuilder.append("V"); + num -= 5; + } else if (num == 4) { + stringBuilder.append("IV"); + num -= 4; + } else { + stringBuilder.append("I"); + num -= 1; + } + } + return stringBuilder.toString(); + } + + public static void main(String[] args) { + Q12 instance = new Q12(); + System.out.println(instance.intToRoman(3)); + System.out.println(instance.intToRoman(9)); + System.out.println(instance.intToRoman(58)); + System.out.println(instance.intToRoman(1994)); + } +} diff --git a/5.leetcode/src/com/fanxb/common/Q13.java b/5.leetcode/src/com/fanxb/common/Q13.java new file mode 100644 index 0000000..f904ed4 --- /dev/null +++ b/5.leetcode/src/com/fanxb/common/Q13.java @@ -0,0 +1,45 @@ +package com.fanxb.common; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created with IntelliJ IDEA + * + * @author fanxb + * Date: 2020/6/10 10:49 + */ +public class Q13 { + private static Map map = new HashMap<>(7); + + static { + map.put('I', 1); + map.put('V', 5); + map.put('X', 10); + map.put('L', 50); + map.put('C', 100); + map.put('D', 500); + map.put('M', 1000); + } + + public int romanToInt(String s) { + int res = 0; + char[] chars = s.toCharArray(); + int length = chars.length; + for (int i = 0; i < length; i++) { + int cur = map.get(chars[i]), next = i == length - 1 ? 0 : map.get(chars[i + 1]); + if (cur < next) { + res += next - cur; + i++; + } else { + res += cur; + } + } + return res; + } + + public static void main(String[] args) { + Q13 instance = new Q13(); + System.out.println(instance.romanToInt("MCMXCIVI")); + } +}