Roman to Integer
Real-world version: Harborside Tally ValueThe statement here is our own: the same inputs, outputs and technique.
Harborside dockhands write whole quantities using a shorthand built from seven marks:
Sstands for 1Hstands for 5Kstands for 10Pstands for 50Tstands for 100Wstands for 500Zstands for 1000
A tally is normally written heaviest mark first, and its quantity is then just the total of its marks, so PKKSS reads 50 + 10 + 10 + 1 + 1 = 72. To keep a tally short a dockhand may put one lighter mark directly in front of a heavier one, and that lighter mark is then taken off the heavier one instead of added to it. Exactly six such pairings are ever written: SH for 4, SK for 9, KP for 40, KT for 90, TW for 400 and TZ for 900.
Given a tally code that a dockhand wrote correctly, return the quantity it stands for.
Examples
Example 1
- Input
- code = "KKSH"
- Output
- 24
Two K marks contribute 10 each, then S sits in front of the heavier H, so that pairing contributes 4.
Example 2
- Input
- code = "ZWTKSH"
- Output
- 1614
The heavy marks add up to 1000 + 500 + 100 + 10, and the trailing pairing adds 4.
Example 3
- Input
- code = "PKKSS"
- Output
- 72
No mark is lighter than the mark to its right, so every mark is simply added.
Constraints
- 1 <= code.length <= 15
- code contains only the characters ('S', 'H', 'K', 'P', 'T', 'W', 'Z')
- code is guaranteed to be a correctly written tally for a quantity in [1, 3999]
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def tally_value(code: str) -> int:public int tallyValue(String code)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Integer to RomanReal-world version: Vault Stroke CodeMedium
- Fraction to Recurring DecimalReal-world version: Ratio Printed as a DecimalMedium
- Smallest Palindromic Rearrangement IIReal-world version: The k-th Mirrored RearrangementHard
- First Unique Character in a StringReal-world version: First Solo StopEasy