Ergodic sampling of the topological charge using the density of states