Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted.
Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted.
def roman(s):
v = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
for i, c in enumerate(s):
if i + 1 < len(s) and v[c] < v[s[i + 1]]: total -= v[c]
else: total += v[c]
return total
print(roman("MMXXIV"), roman("CDXLIX"), roman("XCIX"))What is printed?- A. 2026 449 99
- B. 2024 449 101
- C. 2024 451 99
- D. 2024 449 99
Correct answer: D. 2024 449 99
IV = 4, XL = 40, CD = 400, XC = 90, IX = 9 are the subtractive pairs. MMXXIV = 2000 + 20 + 4; CDXLIX = 400 + 40 + 9; XCIX = 90 + 9. Adding every symbol blindly gives 2026, 671 and 121. O(n).
More Coding Interview Problems questions
- Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a. python def isrot(a, b): return len(a) == len(b) and b in…
- Problem: String t is string s shuffled with one extra letter added. Find the extra letter by XOR-ing all character codes. python from…
- Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …). python def say(s): out, i = [], 0 while i < len(s): j =…
- Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row. python def zigzag(s, rows): if rows ==…
- Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1. python def cmpver(a, b): x…
- Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1…