Last active
January 18, 2019 09:36
-
-
Save somethvictory/8044b8dce4ae6f770712ce87432e8a12 to your computer and use it in GitHub Desktop.
Reverse number algorithm in pure Ruby. No string and array methods which are related to the ordering is allowed.
This file contains 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
# reverse_number(12345) | |
# => 54321 | |
def reverse_number(number) | |
raise 'Input must be number' unless number.is_a? Numeric | |
reversed_numbers = [] | |
# do the operation until all the numbers are modulused and divided | |
loop do | |
# modulus by 10 to get the remaining and add them to the reverse_numbers array | |
reversed_numbers << number % 10 | |
# divide the numbers by 10 to pull out the number which is already added to the reverse_numbers | |
# when numbers / 10 equals to 0 means all the number are accessed | |
break if (number = number / 10) == 0 | |
end | |
sum = 0 | |
digit = 1 | |
length = reversed_numbers.length - 1 | |
# reversly loop through the array | |
(length).downto(0) do |i| | |
# multiple digit by 10 based on the current number position | |
digit = digit * 10 if i < length | |
# sum up all the values and multiply by the digit | |
sum = sum + (reversed_numbers[i] * digit) | |
end | |
sum | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment