+ 1

In the code what does reverse=reverse*10+rem and n/=10 do?

#include <iostream>   using namespace std;   int main()   {   int n, reverse=0, rem;     cout<<"Enter a number: ";     cin>>n;       while(n!=0)       {          rem=n%10;            reverse=reverse*10+rem;          n/=10;       }      cout<<"Reversed Number: "<<reverse<<endl;      return 0;   }  

4th Sep 2019, 12:01 PM
Abir Thapa
Abir Thapa - avatar
3 Answers
+ 3
When you do % 10 to a number you'll get the last digit - the units digit then what it does it gets the units digit and put it in the reverse variable but for not getting the sum of the digits it's also being multiplied by ten for example: First loop: N = 12 Rem = 12 % 10 // 2 Reverse = 0 × 10 + 2 // 2 N /= 10 // 1 Second loop: N = 1 Rem = 1 % 10 // 1 Reverse = 2 × 10 + 1 // 21 N /= 10 // 0 Then now the loop will stop and as you can see the reverse value is 21 - the reversed number of 12.
4th Sep 2019, 12:28 PM
Eliya Ben Baruch
Eliya Ben Baruch - avatar
+ 2
Thx eliya
4th Sep 2019, 12:42 PM
Abir Thapa
Abir Thapa - avatar
+ 1
U r welcome
4th Sep 2019, 12:48 PM
Eliya Ben Baruch
Eliya Ben Baruch - avatar