Skip to content

Instantly share code, notes, and snippets.

@edwardloveall
Last active July 7, 2017 15:23
Show Gist options
  • Select an option

  • Save edwardloveall/29cbe3295f6544c95eeb3ad178935204 to your computer and use it in GitHub Desktop.

Select an option

Save edwardloveall/29cbe3295f6544c95eeb3ad178935204 to your computer and use it in GitHub Desktop.
# An algorithm to reverse a number using only mathematical functions, i.e. no
# String.reverse, or similar. For example, turn `1234` into `4321`.
def reverse_number(number)
digit_count = Math.log10(number).floor + 1
sum = 0
(1..digit_count).each do |power|
ten_to_the_n = 10.0**power
ten_to_the_n_minus_one = 10.0**(power - 1)
remainder = number % ten_to_the_n
digit = (remainder / ten_to_the_n_minus_one).floor
magnitude = digit_count - power
sum += digit * 10**magnitude
end
sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment