We report on the realization of an all-optical transistor by mapping gate and source photons into strongly interacting Rydberg excitations with different principal quantum numbers in an ultracold atomic ensemble. We obtain a record switch contrast of 40% for a coherent gate input with mean photon number one and demonstrate attenuation of source transmission by over ten photons with a single gate photon. We use our optical transistor to demonstrate the nondestructive detection of a single Rydberg atom with a fidelity of 0.72(4).