FastPrepMolecular Weight of a Grouped Formula

Molecular Weight of a Grouped Formula

Agoda logoAgoda● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a valid molecular formula containing only C, H, O, parentheses, and optional single-digit multipliers, return its molecular weight.

Carbon has weight 12, hydrogen has weight 1, and oxygen has weight 8. A multiplier applies to the immediately preceding atom or parenthesized group. Parentheses may be nested.

Function

molecularWeight(formula: String) → int

Examples

Example 1

formula = "H(CH4)2"return = 33

The leading hydrogen weighs 1, while each grouped CH4 weighs 16 and occurs twice.

Example 2

formula = "C(OH)3"return = 39

Carbon contributes 12 and each of the three OH groups contributes 9.

Constraints

  • 1 <= formula.length <= 100.
  • The formula is valid and contains only C, H, O, parentheses, and digits 2 through 9.
  • Every computed weight fits a signed 32-bit integer.

More Agoda problems

See Agoda hiring insights
public int molecularWeight(String formula) {
    // Write your code here.
}
formula"H(CH4)2"
expected33
Checking account…