Problem Instructions Write a program to reverse the digits of a positive integer
ID: 3629714 • Letter: P
Question
Problem InstructionsWrite a program to reverse the digits of a positive integer number. For example, if the number 8735 is entered, the number displayed should be 5378.
(Hint: Use a do statement and continuously strip off and display the number's units digit. If the variable num initially contains the number entered, the units digit is obtained as (num % 10). After a units digit is displayed, dividing the number by 10 sets up the number for the next iteration. Therefore (8735 % 10) is 5 and (8735 / 10) is 873. The do statement should continue as long as the remaining number is not zero.)
Constraints
Make sure the program checks for positive integers only, 1 or greater
If a non-negative number is entered print out: Input Error
Make sure the output is on a single line, no spaces between digits, and no additional text.
Example run 1:
Enter a number to reverse: 8735
5378
Example run 2:
Enter a number to reverse: -453
Input Error
Explanation / Answer
Okay wow, this seemed more complex than it seemed. I'll try to explain this code, but you will really need to study it to see what is going on. Notice my formula "temp+=((num%exp)/(int)pow((double)10,i))*div;" and what iteration of each loop does. I've commented out some of the code, just undo the "//" to see how each part of the formula works.
For example, in the case of input "123", the foruma does as follows:
temp=(3/1*100)=300 For 1st loop
temp=300+(23/10*10)=320 For 2nd loop (*Note how I type casted to do int division so that 23/10=2)
temp=320+(123/100*1)=321 For 3rd loop (Int division again...123/100=1)
Enjoy and please rate!
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num;
cout<<"Enter a number to reverse: ";
cin>>num;
if (num<=0)
{
cout<<"Input Error"<<endl;
exit(1);
}
int temp=num; //Temp holder
int count=0;
int div=1;
//This while loop counts how many digit the number has
while (temp>0)
{
temp/=10;
count++;
div*=10;
}
int exp=1;
for (int i=0; i<count;i++)
{
div/=10;
for (int j=i+1;j>0;j--)
{
exp*=10;
}
temp+=((num%exp)/(int)pow((double)10,i))*div;
//cout<<(num%exp)<<endl;
//cout<<pow((double)10,i)<<endl;
//cout<<div<<endl;
//cout<<temp<<endl;
exp=1;
}
cout<<temp<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.