Linkedin Interview Question for Software Developers


Country: United States




Comment hidden because of low score. Click to expand.
3
of 3 vote

Some facts must be given about roman numerals:
-There are 7 symbols I V X L C D M.
-Each symbol has the following respective integer values 1 5 10 50 100 500 1000.
-The symbols in a roman string are summed in a special way such that the string matches the value known.

Using the information above we can work out a few examples that show us how the value of a roman string is calculated.
Ex 1. LXXXVI =86 this can be expanded into the sum 1 + 5 +10 +10 + 10 + 50.
Ex 2. MDCC =1700 =100 + 100 + 500 + 1000.
Ex 3. IV =4 = 5 + (-1).

Strategy:
Starting from the last symbol of the roman string we add to the total.
Then we go to the next symbol to the left.
If the value of this symbol is smaller than the last symbol we looked at let us subtract it otherwise add it to the total.
Continue onto process symbols like this until we have processed the first symbol of the roman string.

Java Snippet:

int romanNumber(String roman){
		int valueOfLastChar = 0, valueOfCurrentChar =0;
		int total = 0;
	
		for(int i= roman.length()-1; 0<=i; i--){ 
			switch(roman.charAt(i)){
				case 'I': valueOfCurrentChar = 1; break; 
				case 'V': valueOfCurrentChar = 5; break; 
				case 'X': valueOfCurrentChar = 10; break;
				case 'L': valueOfCurrentChar = 50; break;
				case 'C': valueOfCurrentChar = 100; break;
				case 'D': valueOfCurrentChar = 500; break;
				case 'M': valueOfCurrentChar = 1000; break;
			} 

			total += (valueOfCurrentChar < valueOfLastChar) ? -1*valueOfCurrentChar : valueOfCurrentChar;
			valueOfLastChar = valueOfCurrentChar;
		}

		return total;

}

- gfhd760 May 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

What this will do is just go through each character in the string; adding each value to the result. If it is bigger than the previous character, it will subtract 2 * the previous result because you added it once already when you were looking at the previous result.

import java.util.HashMap;
import java.util.Map;

public class RomanNumber {
	
	final static Map<Character, Integer> romanNumberMap = new HashMap<Character, Integer>() {
		{
				this.put('I', 1);
				this.put('V',  5);
				this.put('X', 10);
				this.put('L', 50);
				this.put('C', 100);
				this.put('D', 500);
				this.put('M', 1000);
		}
	};
	
	public static void main(String...args) {
		System.out.println("I=" + romanNumber("I"));
		System.out.println("III=" + romanNumber("III"));
		System.out.println("VI=" + romanNumber("VI"));
		System.out.println("XVI=" + romanNumber("XVI"));
		System.out.println("IV=" + romanNumber("IV"));
		System.out.println("IX=" + romanNumber("IX"));
		System.out.println("XIV=" + romanNumber("XIV"));
		System.out.println("LXIV=" + romanNumber("LXIV"));
	}
	
	public static int romanNumber(String roman) {
		int result = 0;
		char[] romanChars = roman.toCharArray();
		char prevChar = '\0';
		for (Character c : romanChars) {
			if (!romanNumberMap.containsKey(c)) {
				throw new IllegalArgumentException("Not a valid roman number");
			}
			result += romanNumberMap.get(c);
			if (prevChar != '\0' && romanNumberMap.get(prevChar) < romanNumberMap.get(c)) {
				result -= romanNumberMap.get(prevChar) * 2;
			}
			prevChar = c;
		}
		return result;
		
	}

}

- liuben10 April 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class RomanToArabicNumber {

	private static final Map romanToArabic = new HashMap<Character, Integer>();
	
	public static void main(String[] args) {

		romanToArabic.put('I', 1);
		romanToArabic.put('V', 5);
		romanToArabic.put('X', 10);
		romanToArabic.put('L', 50);
		romanToArabic.put('C', 100);
		romanToArabic.put('D', 500);
		romanToArabic.put('M', 1000);
		
		int arabicRepre = toArabic("LXXXVIII");
		System.out.println("value is "+arabicRepre);
	}
	
	private static int toArabic(String romanNum){
		
		int arabicNum = 0;
		if(romanNum == null){
			return arabicNum;
		}
		
		for(int i=romanNum.length()-1; i>=0 ;){
		
			Character firstChar = romanNum.charAt(i);
			int firstCharValue = (int) romanToArabic.get(firstChar);
			if(i-1 >= 0){
				Character secondChar = romanNum.charAt(i-1);
				int secondCharValue = (int)romanToArabic.get(secondChar);
				if(firstCharValue>secondCharValue){
					arabicNum = arabicNum+firstCharValue-secondCharValue;
				}
				else{
					arabicNum = arabicNum+firstCharValue+secondCharValue;
				}
				i=i-2;
			}else{
				arabicNum = arabicNum+firstCharValue;
				i = i-1;
			}
		}
		
		return arabicNum;
	}

}

- skusuj May 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class converter :
    def __init__(self):
        self.romanLetterMap = dict()
        self.romanLetterMap['I']= 1
        self.romanLetterMap["V"] = 5
        self.romanLetterMap["X"] = 10
        self.romanLetterMap["L"] = 50
        self.romanLetterMap["C"] = 100
        self.romanLetterMap["D"] = 500
        self.romanLetterMap["M"] = 1000
        print(self.romanLetterMap)
    
    def convertToRoman(self,roman):
        if roman is None or len(roman) <= 0 :
            return None
        prev=None
        result = 0
        for i in range(len(roman)):
            romanLetter = roman[i]
            if romanLetter not in self.romanLetterMap:
                print("invalid letter sequence")
                break
            result += self.romanLetterMap[romanLetter]
            if prev is not None and self.romanLetterMap[prev] < self.romanLetterMap[romanLetter]:
                result -= 2* self.romanLetterMap[prev]
            prev = romanLetter
        return result   
            


c = converter()
print("IV = ", c.convertToRoman("IV"))
print("X = ", c.convertToRoman("X"))
print("IX = ", c.convertToRoman("IX"))
print("XI = ", c.convertToRoman("XI"))
print("XIV = ", c.convertToRoman("XIV"))

- Jijo June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class converter :
    def __init__(self):
        self.romanLetterMap = dict()
        self.romanLetterMap['I']= 1
        self.romanLetterMap["V"] = 5
        self.romanLetterMap["X"] = 10
        self.romanLetterMap["L"] = 50
        self.romanLetterMap["C"] = 100
        self.romanLetterMap["D"] = 500
        self.romanLetterMap["M"] = 1000
        print(self.romanLetterMap)
    
    def convertToRoman(self,roman):
        if roman is None or len(roman) <= 0 :
            return None
        prev=None
        result = 0
        for i in range(len(roman)):
            romanLetter = roman[i]
            if romanLetter not in self.romanLetterMap:
                print("invalid letter sequence")
                break
            result += self.romanLetterMap[romanLetter]
            if prev is not None and self.romanLetterMap[prev] < self.romanLetterMap[romanLetter]:
                result -= 2* self.romanLetterMap[prev]
            prev = romanLetter
        return result   
            


c = converter()
print("IV = ", c.convertToRoman("IV"))
print("X = ", c.convertToRoman("X"))
print("IX = ", c.convertToRoman("IX"))
print("XI = ", c.convertToRoman("XI"))
print("XIV = ", c.convertToRoman("XIV"))

- jijojohn88 June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int romanToInt(string s) {
        int num = 0;
        for(int i = 0;  i < s.length(); i++ )
        {
            switch(s[i])
            {
                case 'M':
                    num += 1000;
                    break;
                case 'D':
                    num += 500;
                    break;
                case 'C':
                    num += 100;
                    break;
                case 'L':
                    num += 50;
                    break;
                case 'X':
                    num += 10;
                    break;
                case 'V':
                    num += 5;
                    break;
                case 'I':
                    num += 1;
                    break;
            }
            if( i > 0)
            {
                switch(s[i-1])
                {
                    case 'C':
                        if( s[i] == 'D' || s[i] == 'M')
                            num -=200;
                        break;
                    case 'X':
                        if( s[i] == 'C' || s[i] == 'L')
                            num -=20;
                        break;
                    case 'I':
                        if( s[i] != 'I')
                            num -=2;
                        break;
                }
            }
        }
        return num;
    }

- Shrek June 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class RomanNumber {

	private static final Map<Character, Integer> romanNumberMap;
	static {
		Map<Character, Integer> initMap = new HashMap<Character, Integer>();
		initMap.put('I', 1);
		initMap.put('V', 5);
		initMap.put('X', 10);
		initMap.put('L', 50);
		initMap.put('C', 100);
		initMap.put('D', 500);
		initMap.put('M', 1000);
		romanNumberMap = Collections.unmodifiableMap(initMap);
	}

	public static void main(String[] args) {
		System.out.println(romanNumber("MMCCCXLIX"));
	}

	private static int romanNumber(String string) {
		char[] charArr = string.toCharArray();
		int retVal = 0;
		int prev = 0;

		for (int i = 0; i < charArr.length; i++) {
			if (i > 0)
				prev = romanNumberMap.get(charArr[i - 1]);
			retVal += romanNumberMap.get(charArr[i]);
			if (romanNumberMap.get(charArr[i]) > prev) {
				retVal -= prev * 2;
			}
		}
		return retVal;
	}

}

- nb_brain August 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class RomanNumber {

	private static final Map<Character, Integer> romanNumberMap;
	static {
		Map<Character, Integer> initMap = new HashMap<Character, Integer>();
		initMap.put('I', 1);
		initMap.put('V', 5);
		initMap.put('X', 10);
		initMap.put('L', 50);
		initMap.put('C', 100);
		initMap.put('D', 500);
		initMap.put('M', 1000);
		romanNumberMap = Collections.unmodifiableMap(initMap);
	}

	public static void main(String[] args) {
		System.out.println(romanNumber("MMCCCXLIX"));
	}

	private static int romanNumber(String string) {
		char[] charArr = string.toCharArray();
		int retVal = 0;
		int prev = 0;

		for (int i = 0; i < charArr.length; i++) {
			if (i > 0)
				prev = romanNumberMap.get(charArr[i - 1]);
			retVal += romanNumberMap.get(charArr[i]);
			if (romanNumberMap.get(charArr[i]) > prev) {
				retVal -= prev * 2;
			}
		}
		return retVal;
	}

}

- nb_brain August 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Strategy: Read string and add values to a stack.
Then pop the stack and increment result while remembering the max. value encountered.
If new value is smaller than max value encountered, substract.

def roman_to_int(roman):
    valid_dict = dict((k,v) for k, v in zip('ivxcdm', [1, 5, 10, 100, 500, 1000]))

    values = []
    for char in roman.lower():
        if char in valid_dict:
            values.append(valid_dict[char])
        else:
            raise KeyError("Roman number is not valid.")

    max_val = 0
    result = 0
    while values:
        val = values.pop()
        if val >= max_val:
            max_val = val
            result += val
        elif val < max_val:
            result -= val
    return result

if __name__ == '__main__':
    print roman_to_int('XCVI') # 96
    print roman_to_int('XCIX') # 99
    print roman_to_int('XXXV') # 35

- Nathan Kiner August 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int GetInteger(char digit)
{
	if (digit ==  'I')
		return 1;
	if (digit ==  'V')
		return 5;
	if (digit ==  'X')
		return 10;
	if (digit ==  'L')
		return 50;
	if (digit ==  'C')
		return 100;
	if (digit ==  'D')
		return 500;
	if (digit ==  'M')
		return 1000;
	return 0;
}

int RomanToInt(std::string roman)
{
	int previousDigit = GetInteger(roman[roman.size() - 1]);
	int result = previousDigit;
	for(int i = roman.size() - 2; i >= 0; i--)
	{
		int currentDigit = GetInteger(roman[i]);
		if (currentDigit < previousDigit)
		{
			result += currentDigit * -1;
		}
		else
		{
			result += currentDigit;
		}
		
		previousDigit = currentDigit;
	}
	
	return result;
}

int main()
{
    std::string roman = "MCMLXXXVI";
    std::cout<<RomanToInt(roman);
    return 0;
}

- Gyan Garcia April 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import re


numerals = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
            "XC": 90, "L": 50, "XL": 40, "X": 10, "V": 5, "IV": 4, "I": 1}
r = re.compile('|'.join(sorted(numerals.keys(), key=len, reverse=True)))


def to_roman(n, s=''):
    for num, val in numerals.items():
        if n // val:
            n -= val
            s += num
            return to_roman(n, s)
    if not n:
        return s


def to_int(s):
    tokens = r.findall(s)
    return sum(numerals[t] for t in tokens)

- RG August 10, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import re


numerals = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
            "XC": 90, "L": 50, "XL": 40, "X": 10, "V": 5, "IV": 4, "I": 1}
r = re.compile('|'.join(sorted(numerals.keys(), key=len, reverse=True)))


def to_roman(n, s=''):
    for num, val in numerals.items():
        if n // val:
            n -= val
            s += num
            return to_roman(n, s)
    if not n:
        return s


def to_int(s):
    tokens = r.findall(s)
    return sum(numerals[t] for t in tokens)

- Robert Graham August 10, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More