John Quincy Adams was the only president who did not win by popular vote or electoral college. He was elected by the US House of Representatives when the electoral college failed to have a candidate get enough votes to win.

Heaven only knows what would happen if something like this happened today.