15,962,563 members
See more:
I want to reverse 8970 as 0798 and
0987 as 7890
-987 as -789
the problem I'm getting is with second and third case.

What I have tried:

```#include<iostream>
#include <string>
using namespace std;

int reverseDigits(int num)
{
string strin=to_string(num);   //covert integer to char to print zero.
reverse(strin.begin(), strin.end());
num=stoi(strin);
cout<<"Reverse of num entered: ";
for(char p:strin){
cout<<p;
}

return 0;
}

int main(){
int num;
cout<<"Enter a number : ";
cin>>num;
reverseDigits(num);
cout<<endl<<endl;
cout<<code by vksssd;
return 0;
}```
Posted
Updated 16-Nov-21 20:12pm
v3

## Solution 3

Quote:
How to reverse digits of number in cpp?

Do not use integer, use string. With integers, any input with leading 0 will fail.
Treat the problem like text. Like "code" => "edoc".

Vedaanti Badwaik 26-Aug-22 6:56am
Write a program in c++ to find absolute difference between the original number and it's reversed number
Patrice T 26-Aug-22 7:01am
Why should I ?

## Solution 2

You can reverse a number without converting tit to a string: if you take the log base 10 of a number, the integer part is the number of digits in the number minus one: C library function - log10()[^] This gives you a for loop :
C++
```int digits = (int) log10(num) + 1;
for (int i = 0; i < digits; i++)
{
...
}```
Inside the loop, you can extract the least significant digit using the modulus operator, and prepare the number for the next time round the loop by dividing it by ten.

Give it a try, it's quick, efficient, and easy to code!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 40 RickZeeland 15 Dave Kreskowiak 10 Pete O'Hanlon 10
 OriginalGriff 218 Pete O'Hanlon 150 merano99 80 den2k88 50 Andre Oosthuizen 50

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900