Introduction
In this challenge, you will be tasked with creating a function that reverses a given number. The function should take a number as an argument and return the reverse of that number.
Reverse Number
Write a function reverse_number(n) that takes a number as an argument and returns the reverse of that number. The function should meet the following requirements:
- The function should reverse the number, regardless of whether it is positive or negative.
- The function should return a float if the input is a float, and an integer if the input is an integer.
- The function should not use any built-in functions that directly reverse a number (e.g.
reversed()). - The function should not use any built-in functions that directly convert a number to a string (e.g.
str()). - The function should not use any built-in functions that directly convert a string to a number (e.g.
int()orfloat()).
from math import copysign
def reverse_number(n):
return copysign(float(str(n)[::-1].replace('-', '')), n)
reverse_number(981) ## 189
reverse_number(-500) ## -5
reverse_number(73.6) ## 6.37
reverse_number(-5.23) ## -32.5
Summary
In this challenge, you have learned how to reverse a number using Python. You have also learned how to handle both positive and negative numbers, as well as floats and integers. Keep practicing and exploring Python to become a better programmer!