How to reverse a negative number in python
I am learning python and I meet some troubles. Show I want to write the script to reverse a negative integer " -1234 to 4321- " and non-integer " 1.234 to 432.1". please help me. P.S. cannot use "str()" function I just only can write the script to reverse positive integer 1234 to 4321
smac89 35.1k14 gold badges115 silver badges162 bronze badges asked Apr 28, 2015 at 17:24
6
#output cba 321 -321 answered Jul 5, 2021 at 14:21
1 how
about using your code, but just concatenate a rev_int.py:
This produces:
answered Apr 28, 2015 at 17:55
CuriousCurious 2,6281 gold badge29 silver badges40 bronze badges 6 Using SLICING EASILY DONE IT
answered Mar 23, 2021 at 6:35
Below code runs fine on Python-3 and handles positive and negative integer case. Below code takes STDIN and prints the output on STDOUT.
answered Aug 24, 2021 at 17:43
Ankit RajAnkit Raj 8491 gold badge7 silver badges17 bronze badges Using str convert method.
answered May 11 at 9:46
1 Use this as a guide and make it work for floating point values as well:
answered Apr 28, 2015 at 17:43
smac89smac89 35.1k14 gold badges115 silver badges162 bronze badges 2 Why not just do the following?:
These would print 54321.1 and 54321-. Lol, I don't understand the down-vote.. I guess this is too simple and doesn't require over complicating the process to get to the same result? Does this not solve the problem at hand no matter the number used? answered Apr 28, 2015 at 18:30
AaronAaron 11 bronze badge 2 What is the reverse of a negative number?Step 1: Check if the number is negative or not. If the number is negative, multiply it with -1 to make it positive. We will multiply the reversed number with -1 at the last to giving a similar effect as if the negative number was reversed. Step 2: Initialize a variable reverse to 0.
How do you reverse a value in Python?Example 1: Reverse a Number using a while loop
First, the remainder of the num divided by 10 is stored in the variable digit . Now, the digit contains the last digit of num , i.e. 4. digit is then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in the reversed number.
How does Python handle negative numbers?When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number. Another method is to subtract the given positive number by zero. It will return the negative form of the given number.
Can you reverse integers in Python?Python makes it easy to reverse a number by using a while loop. We use a while loop with the help of both floor division and the modulus % operator.
|