Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Write a program in c++ to find absolute difference between the original number and it's reversed number


What I have tried:

Yes I have tried it but I am very confused about how to solve this,and what would be the solution for it
Posted
Updated 26-Aug-22 1:51am

What's wrong with:
C++
#include <iostream>
using namespace std;

unsigned rev(unsigned u)
{
  unsigned ru = 0;
  while (u)
  {
    ru = ru * 10 + u % 10;
    u /= 10;
  }
  return ru;
}

unsigned uabs(unsigned u1, unsigned u2)
{
  if ( u2 < u1 )
  {
    return (u1-u2);
  }
  return (u2-u1);
}

int main()
{

  unsigned u;
  cout << "please enter a not-negative number: ";
  cin >> u;

  cout << "the asolute difference between the original number and the reversed one is " << uabs(u, rev(u)) << "\n";
}
?
 
Share this answer
 
Comments
Patrice T 26-Aug-22 7:52am    
+5
CPallini 26-Aug-22 8:02am    
Thank you.
Patrice T 26-Aug-22 8:05am    
By the way, you can simplify your code, see S4.
CPallini 26-Aug-22 8:44am    
Well, you have to use abs((long long) u1 - u2), which is ugly.
Dave Kreskowiak 26-Aug-22 8:50am    
You have a nasty habit of doing someone's homework for them. That takes them out of the process of learning through failure and thinking about the problem.
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
 
Share this answer
 
Quote:
C++
/* Find Absolute Difference */
if (input < reverseInteger(input)) {
    input = reverseInteger(input); // If the result will be negative, reverse the number before finding the difference
    input -= reverseInteger(input);
}
else {
    input -= reverseInteger(input);
}

You can always make things as complicated as you want, but :
C++
AbsoluteDifference= abs( A - B );

is simpler
 
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