Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse the position of integer digits?

Tags:

c++

logic

i have to reverse the position of integer like this

input = 12345

output = 54321

i made this but it gives wrong output e.g 5432

#include <iostream>
using namespace std;

int main(){
 int num,i=10;   
 cin>>num;   

 do{
    cout<< (num%i)/ (i/10);
    i *=10;
   }while(num/i!=0);

 return 0;
}
like image 911
bbjkdsfj Avatar asked Jan 26 '11 15:01

bbjkdsfj


People also ask

What is reversing of digits?

Reversible numbers, or more specifically pairs of reversible numbers, are whole numbers in which the digits of one number are the reverse of the digits in another number, for example, 2847 and 7482 form a reversible pair.

How do you find the reverse of a number?

Reverse an Integer In each iteration of the loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times. Inside the loop, the reversed number is computed using: reverse = reverse * 10 + remainder; Let us see how the while loop works when n = 2345 .


2 Answers

Here is a solution

    int num = 12345;
    int new_num = 0;
    while(num > 0)
    {
            new_num = new_num*10 + (num % 10);
            num = num/10;
    }
    cout << new_num << endl;
like image 121
Elalfer Avatar answered Oct 24 '22 17:10

Elalfer


Your loop terminates too early. Change

}while(num/i!=0);

to

}while((num*10)/i!=0);

to get one more iteration, and your code will work.

like image 21
Doug T. Avatar answered Oct 24 '22 17:10

Doug T.