Skip to the content

Atoms in the formula

Problem

The formula for glucose is C6H12O6: six carbon atoms, twelve hydrogen and six oxygen, 24 in all. The lab wants that total for any formula, and working it out is up to you.

Write a function that takes the formula as text and returns the total number of atoms, as a whole number. The formula is a row of elements, with no spaces or parentheses, and it has at least one. Each element is an uppercase letter, maybe followed by a lowercase letter that belongs to the same name (Na is a single element), and maybe followed by a whole number greater than 0, which can have several digits. That number says how many atoms of that element there are; with no number, there is just one. So H2O gives 3, CO2 gives 3 and NaCl gives 2.

Examples

  • Glucose

    "C6H12O6" → 24

  • The last one with no number

    "H2O" → 3

  • The first one with no number

    "CO2" → 3

  • Two-letter names

    "NaCl" → 2

  • Two with no number in a row

    "C2H5OH" → 9

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def count_atoms(formula):
    pass

JavaScript

function countAtoms(formula) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →