176k views
3 votes
Write a function, reverseDigit, that takes an integer as a parameter and returns the number with its digits reversed. For example: the value of reverseDigit(12345) is 54321; the value of reverseDigit(5600) is 65; the value of reverseDigit(7008) is 8007; and the value of reverseDigit(–532) is –235

2 Answers

2 votes

Final answer:

The function 'reverseDigit' can be created in a programming language like Python to reverse the digits of an integer by handling the integer as a string and then reconverting it to an integer, taking care to preserve the sign for negative numbers.

Step-by-step explanation:

Function to Reverse Digits of an Integer

To write a function called reverseDigit that reverses the digits of an integer, one can convert the integer to a string, reverse the string using slicing, and then convert it back to an integer. If the input number is negative, this operation needs to account for the negative sign. Here is an example of how this can be implemented in Python:

def reverseDigit(num):
if num < 0:
return -int(str(-num)[::-1])
else:
return int(str(num)[::-1])

Let's take a look at some examples:

  • reverseDigit(12345) would return 54321.
  • reverseDigit(5600) would return 65, because the leading zeroes are dropped when the number is converted back to an integer.
  • reverseDigit(7008) would return 8007.
  • reverseDigit(-532) would return -235, with the negative sign preserved.

This function can handle both positive and negative integers and will always return the integer with its digits reversed.

User Raymkchow
by
4.0k points
6 votes

Answer:

This program is written in C++. You can implement this program in any language. The code along with comments is given below in explanation section.

Step-by-step explanation:

#include <iostream>

using namespace std;

int main() // main function

{

int number, reverseNumber=0, reminder; //varible declaration

cout<<"Enter a number: "; //prompt user to enter the number

cin>>number; //save the entered number into number variable

while(number!=0) //while number does not become zero.... remain in loop

{

reminder=number%10; // taken reminder of number

reverseNumber=reverseNumber*10+reminder; //store the number digit into reverse order

number/=10; //decrease the number or shift the division to next digit

}

cout<<"Reversed Number: "<<reverseNumber<<endl; //print reversed number.

return 0;

}

User Sladix
by
4.5k points