Last active
December 2, 2022 04:01
-
-
Save EricBallard/0524f6a64cf4b80d42379abb66d1fc06 to your computer and use it in GitHub Desktop.
IntegertoRoman.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static void main(String[] args) { | |
| System.out.println(new Solution().romanToInt("MCMXCIV")); | |
| } | |
| static class Solution { | |
| private int getTotal(String s, char c, int index, int size) { | |
| if (index == size - 1) return -1; | |
| char cc = s.charAt(index + 1); | |
| switch (c) { | |
| case 'I': | |
| return cc == 'V' ? 4 : cc == 'X' ? 9 : 1; | |
| case 'X': | |
| return cc == 'L' ? 40 : cc == 'C' ? 90 : 10; | |
| case 'C': | |
| return cc == 'D' ? 400 : cc == 'M' ? 900 : 100; | |
| default: | |
| return 0; | |
| } | |
| } | |
| public int romanToInt(String s) { | |
| int len = s.length(); | |
| int total = 0; | |
| for (int i = 0; i < len; i++) { | |
| char c = s.charAt(i); | |
| int t; | |
| switch (c) { | |
| case 'I': | |
| t = getTotal(s, c, i, len); | |
| total += (t == -1 ? 1 : t); | |
| if (t != 1) i++; | |
| break; | |
| case 'V': | |
| total += 5; | |
| break; | |
| case 'X': | |
| t = getTotal(s, c, i, len); | |
| total += (t == -1 ? 10 : t); | |
| if (t != 10) i++; | |
| break; | |
| case 'L': | |
| total += 50; | |
| break; | |
| case 'C': | |
| t = getTotal(s, c, i, len); | |
| total += (t == -1 ? 100 : t); | |
| if (t != 100) i++; | |
| break; | |
| case 'D': | |
| total += 500; | |
| break; | |
| case 'M': | |
| total += 1000; | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| return total; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer provided for LeetCode question:
https://leetcode.com/problems/roman-to-integer/description/
"Runtime 4 ms Beats 95.96% Memory 42.3 MB Beats 95.17%"