Question 1
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
This problem is not hard, But too many cases you need to consider, the code will be long to read.
http://www.rapidtables.com/convert/number/date-to-roman-numerals.htm
Got to this link to look some info. for Roman Number if you are not familiar with them like me.
Below is the initial one I thougt,
public class Solution { public int romanToInt(String s) { if (s==null || s.length()<1) return 0; s = s.trim(); int i = 0; int result = 0; while (i < s.length()) switch(s.charAt(i)){ case 'I': i ++; if (i < s.length()){ switch(s.charAt(i)){ case 'V': result += 4; i ++; break; case 'X': result += 9; i ++; break; default: result += 1; break; } } else result += 1; break; case 'V': i ++; result += 5; break; case 'X': i ++; if (i < s.length()){ switch(s.charAt(i)){ case 'L': result += 40; i ++; break; case 'C': result += 90; i ++; break; default: result += 10; break; } } else result += 10; break; case 'L': i ++; result += 50; break; case 'C': i ++; if (i < s.length()){ switch(s.charAt(i)){ case 'D': result += 400; i ++; break; case 'M': result += 900; i ++; break; default: result += 100; break; } } else result += 100; break; case 'D': i ++; result += 500; break; case 'M': i ++; result += 1000; break; default: return 0; } return result; } }
Then I make a better one, seems a litter cleaner.
public class Solution { public int parseRomanNum(Character c){ switch (c){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } public int romanToInt(String s) { if (s==null || s.length()<1) return 0; s = s.trim(); int result = parseRomanNum(s.charAt(0)); for (int i = 1; i < s.length(); i ++){ int pre = parseRomanNum(s.charAt(i-1)); int cur = parseRomanNum(s.charAt(i)); if (pre >= cur) result += cur; else result = result - pre*2 + cur; } return result; } }