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".

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:**

0987 as 7890

-987 as -789

the problem I'm getting is with second and third case.

#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; }

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".

Permalink

Share this answer

Comments

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 ?

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 :

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

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!

Permalink

Share this answer

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

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