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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With