Interview Questions

Given a Roman number, convert it into the decimal number....

Microsoft Interview Questions and Answers


(Continued from previous question...)

68. Given a Roman number, convert it into the decimal number....

Question:
Given a Roman number, convert it into the decimal number. Write the code considering the all cases including invalid strings.


maybe an answer1:

#include <stdio.h>
#include <string.h>
int RomanNumeral[]={0,0,100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10,0,0};

int RomanToDecimal (char* pRoman)
{
int decimalVal=0,curVal=0,prevVal=0,index=0;
int curMax=-1,curIndex=strlen(pRoman)-1;
while(curIndex >= 0)
{
if((pRoman[curIndex] >= 'a') && (pRoman[curIndex] <= 'z'))
{
index=pRoman[curIndex]-'a';
}
else if((pRoman[curIndex] >= 'A') && (pRoman[curIndex] <= 'Z'))
{
index=pRoman[curIndex]-'A';
}
else
{
printf("Invalid String\n");
return curVal;
}
prevVal=curVal;
curVal = RomanNumeral[index];
if(curVal == 0)
{
printf("Invalid String\n");
return curVal;
}
if(curVal < curMax)
{
if((curVal < prevVal)&&(prevVal != curMax))
{
decimalVal = decimalVal + curVal;
}
else
{
decimalVal = decimalVal - curVal;
}
}
else
{
decimalVal = decimalVal + curVal;
curMax = curVal;
}
--curIndex;
}
return decimalVal;
}
int main()
{
char RomanNum[50];
gets(RomanNum);
printf("Roman Num: %s\nDecimal Num: %d\n",\
RomanNum, RomanToDecimal(RomanNum));
return 0;
}



maybe an answer2:

class RomanDecimalTransformer {

public static boolean isValidRomanNumeral(String romanNumeral) {
if (romanNumeral == null || romanNumeral.length() == 0) {
return false;
}

String regEx4RomanNumbers = "M{0,3}(CM|C{2,3}|CD?+|DC{0,3})?+(XC|X{2,3}|XL?+|LX{0,3})?+(IX|I{2,3}|IV?+|VI{0,3})?+";

return romanNumeral.toUpperCase().matches(regEx4RomanNumbers); }

public static int romanToDecimal(String romanNumeral) {
if (!isValidRomanNumeral(romanNumeral)) {
return -1;
}

char[] r = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' };
int[] d = { 1000, 500, 100, 50, 10, 5, 1 };
int result = 0;
int prev = Integer.MAX_VALUE;
for (char c : romanNumeral.toUpperCase().toCharArray()) {
for (int j = 0; j < r.length; ++j) {
if (c == r[j]) {
result += d[j];
if (d[j] > prev) {
result -= prev << 1;
}
prev = d[j];
}
}
}
return result;
}
}

(Continued on next question...)

Other Interview Questions