Show problems as
Classic problem #13EasyHash TableMathString

Roman to Integer

Real-world version: Harborside Tally Value
Tracked in this browser only
Read Roman to Integer on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Harborside dockhands write whole quantities using a shorthand built from seven marks:

  • S stands for 1
  • H stands for 5
  • K stands for 10
  • P stands for 50
  • T stands for 100
  • W stands for 500
  • Z stands 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.

Python
def tally_value(code: str) -> int:
Java
public int tallyValue(String code)