2013년 2월 18일 월요일

Roman to Integer

 public int romanToInt(String s) {
  int rv = 0;
  int len = s.length();

  int currentDigit = 0;
  int prevValue = 0;
  for (int i = 0; i < len; i++) {
   char c = s.charAt(i);

   int currentValue = 0;
   switch (c) {
   case 'M':
    currentValue = 1000;
    break;
   case 'D':
    currentValue = 500;
    break;
   case 'C':
    currentValue = 100;
    break;
   case 'L':
    currentValue = 50;
    break;
   case 'X':
    currentValue = 10;
    break;
   case 'V':
    currentValue = 5;
    break;
   case 'I':
    currentValue = 1;
    break;
   }

   if (prevValue == 0) {
    currentDigit += currentValue;
    prevValue = currentValue;
   } else if (currentValue == prevValue) {
    currentDigit += currentValue;
   } else if (currentValue > prevValue) {
    rv += currentValue - currentDigit;
    prevValue = 0;
    currentDigit = 0;
   } else {
    rv += currentDigit;
    prevValue = currentValue;
    currentDigit = currentValue;
   }
  }

  rv += currentDigit;
  return rv;
 }

댓글 없음:

댓글 쓰기