Reverse a negative number in Python | Generally, To reverse a number we need to extract the last digit of the number and add that number into a temporary variable with some calculation, then remove the last digit of the number. Do these processes until the number becomes zero.
To remove the last digit the modulus operator (%) will be helpful for us, and to remove the last digit division operator (/) can be used. To add the last digit first we need to multiply the previous value by 10. Once you get the logic, you can write the program in any language.
But in this program, we reverse a negative number in python. So, we cannot find the reverse of the negative number using the above method. To reverse a negative number using the slicing operator and str() function.
How to Reverse a Negative Number in Python
We read a negative number and reverse a negative number using slice operations. We will convert the integer number to string using str() and then, calculate the reverse of a number using the slicing operation.
Syntax of slicing operation:- str(num) [::-1]
# Python program to reverse a negative number
def reverseNum(n): #user-defined function
n = str(n)
if n[0] == '-':
a = n[::-1]
return f"{n[0]}{a[:-1]}"
else:
return n[::-1]
# take inputs
num = '-123'
# calling function and display result
print('The reverse number is =', reverseNum(num))
Output:-
The reverse number is = -321
Reversing a Negative Number in Python
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse a negative number
def reverseNum(n): #user-defined function
n = str(n)
if n[0] == '-':
a = n[::-1]
return f"{n[0]}{a[:-1]}"
else:
return n[::-1]
# take inputs
num = input('Enter the number: ')
# calling function and display result
print('The reverse number is =', reverseNum(num))
Output for the input values test-case-1:-
Enter the number: -165
The reverse number is = -561
Output for the input values test-case-2:-
Enter the number: 456416
The reverse number is = 614654
Output for the input values test-case-3:-
Enter the number: -16309792
The reverse number is = -29790361
Reverse a Negative Number in Python
This python program performs the same task. But this is the shortest and easiest way to write the previous python program.
# Python program to reverse a negative number
def reverseNum(n): #user-defined function
if n >= 0:
return int(str(n)[::-1])
else:
return int('-{val}'.format(val = str(n)[1:][::-1]))
# take inputs
num = int(input('Enter the number: '))
# calling function and display result
print('The reverse number is =', reverseNum(num))
Output:-
Enter the number: -15097
The reverse number is = -79051