re: Daily Coding Puzzles - Oct 29th - Nov 2nd VIEW POST

re: Wednesday Write a program to reverse the digits of a positive integer but without converting it to a string.


let rec loop rev i =
    if i = 0 then rev
    else loop (rev * 10 + (i % 10)) (i / 10)

// usage, returns 987654321
let reversed = loop 0 123456789
  • Uses a recursive loop. (F# will TCO to a while loop on compile)
  • i % 10 gets the right-most digit of i
  • rev * 10 shifts the numbers left, with right-most zero
  • i / 10 shifts the numbers right, dropping right-most digit

I happened to remember these little number tricks from a previous challenge. This is basically using integers as digit stacks.

code of conduct - report abuse