This is very well explained here https://medium.com/@ManBearPigCode/how-to-reverse-a-number-mathematically-97c556626ec6