Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse integer digits

Tags:

ruby

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?

like image 854
Sahil Dhankhar Avatar asked Dec 10 '13 08:12

Sahil Dhankhar


2 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
like image 147
Tom Lord Avatar answered Sep 28 '22 16:09

Tom Lord


Here is another way without converting string....

x = 12345
y = 0

while x > 0 do
    y = y*10
    y = y + (x%10)
    x = x/10 

  puts y      
end

This algorithm can be asked in many interviews as well....not matter which language you use....this logic will be same. above example using Ruby

like image 41
Rameshwar Vyevhare Avatar answered Sep 28 '22 15:09

Rameshwar Vyevhare