Reversing an integer

Viewed 2845

I am trying to write a function which takes an input number and outputs the number in reverse order.

Ie:

Input -> 25 Output -> 52

Input -> 125 Output -> 521

I am new to lisp, if its helpful here is the working function in c++

function.cpp

int revs(int rev, int n)
{
  if (n <= 0)
    return rev;

  return revs((rev * 10) + (n % 10), n/10);
}

I have written it in Racket as follows:

(define (revs rev n)
  (if (<= n 0)
     rev
     (revs (+ (* rev 10) (modulo n 10)) (/ n 10))))

But when I run it with (revs 0 125) I get this error:

modulo: contract violation
  expected: integer?
  given: 25/2
  argument position: 1st
  other arguments...:
   10

Certainly I am doing something incorrect here, but I am unsure of what I am missing.

5 Answers

With recursion, you can do something like:

#lang racket

(define (reverse-num n)
  (let f ([acc 0]
          [n n])
    (cond
      [(zero? n) acc]
      [else (f (+ (* acc 10) (modulo n 10)) (quotient n 10))])))
Related