Molar Mass
Time limit1sMemory limit128 MB
The program parses each formula of C, H, O, and N with optional atom counts and prints its molar mass using the given weights.
- Level
Easy2 of 10
- Topics
- String, Implementation
- Solved
- No attempts yet
Problem

An organic compound is any member of a large class of chemical compounds whose molecules contain carbon. The molar mass of an organic compound is the mass of one mole of that compound, and it can be computed from the standard atomic weights of the elements.
Given a molecular formula, Dr. CHON wants to find its molar mass. A molecular formula such as C3H4O3 identifies each constituent element by its chemical symbol and gives the number of atoms of that element in one molecule of the compound. When a molecule contains more than one atom of an element, the count is written as a subscript after the chemical symbol.
In this problem, assume that a molecular formula is made up of only the four elements 'C' (carbon), 'H' (hydrogen), 'O' (oxygen), and 'N' (nitrogen), and contains no parentheses.
The table below gives the standard atomic weights of 'C', 'H', 'O', and 'N'.
For example, the molar mass of the formula C6H5OH is g/mol. Given a molecular formula, write a program that computes its molar mass.
Input
Your program reads from standard input. The input consists of test cases. The number of test cases is given on the first line. Each test case is given on a single line containing one molecular formula as a string. Chemical symbols are given as capital letters, and the length of the string is greater than 0 and less than 80. The count that follows a chemical symbol is omitted when it is 1; otherwise .
Output
Your program writes to standard output. Print exactly one line for each test case. The line contains the molar mass of the given molecular formula, printed to exactly three decimal places.