Reverse integer digits

Viewed 10292

I was trying to reverse the digits of an integer: 123456 => 654321, and the best solution that I could come up with was 123456.to_s.reverse.to_i. I feel that this is too much of code. Anyone have a better approach than this?

6 Answers

This is a very "code golf"-ish answer, and not something I'd suggest writing in real code...

But you can shave an extra character off the answer with:

123456.to_s.reverse.to_i
123456.digits.join.to_i

Or (again, only as a 'code golf' answer!!) if you're happy to end up with a String rather than an Integer, you can make this even sorter with:

123456.digits*''  #=> "654321"

In fact, converting to a string might actually be preferable, because it may prevent loosing information from missing zeros. Code-golf answers aside, compare:

43210.to_s.reverse #=> "01234"
43210.to_s.reverse.to_i #=> 1234

I think there're only two ways to achieve that in general:

1.

n = whatever
result = 0
while n > 0
  d, m = n.divmod(10)
  result = result * 10 + m
  n = d
end

2. Convert to str, reverse, convert back (you did this).

Computer memory is binary so it has no idea of decimal (I hope this is the right word) digits so you need to "introduce" them.

Here's a fast one-liner for various online competitions for positive integers:

number = 123456778
p 0.then { |ch|  (number./(10).tap { |x| ch, number = ch * 10 + (number - x  * 10), x } while (number > 0)) || ch }

But this is unreadable. To make it readable:

#!/usr/bin/ruby -w

number = 123

ch = 0

while (number > 0)
    div = number / 10
    mod = number - div  * 10

    ch = ch * 10 + mod
    number = div
end

p ch

Dealing with negative integers:

#!/usr/bin/ruby -w

number = -123

ch = 0

negative = number < 0
number *= -1 if negative

while (number > 0)
    div = number / 10
    mod = number - div  * 10

    ch = ch * 10 + mod
    number = div
end

ch *= -1 if negative

p ch

Using Kernel#then() and Kernel#tap() will also enable you to write this in one line, the ugliest way.

Reverse digits of an integer in Javascript

Solution

var reverse = function(x) {
  let result = 0
  while (x) {
    result = result * 10 + x % 10
    x = x / 10 | 0
  }
  return Math.abs(result) > 2147483647 ? 0 : result
};

Input Example

console.log(reverse(-1254))

Output

-4521
Related