Last active
July 7, 2017 15:23
-
-
Save edwardloveall/29cbe3295f6544c95eeb3ad178935204 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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