Molecular Weight of a Grouped Formula
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) → intExamples
Example 1
formula = "H(CH4)2"return = 33The leading hydrogen weighs 1, while each grouped CH4 weighs 16 and occurs twice.
Example 2
formula = "C(OH)3"return = 39Carbon 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 digits2through9. - Every computed weight fits a signed 32-bit integer.