DEV Community 👩‍💻👨‍💻

Shakeeb Shahid
Shakeeb Shahid

Posted on

Shakeeb's Algorithm to reverse a number. Crisp and very logical. Dont memorise 😂😂😁

`#include
using namespace std;
int reverse(int n)
{
//Count numbers first
int count = 0;
int orig = n;
while(n>0)
{
count++;
n=n/10;
}
//REVERSE USING PLACE VALUES;
//Input: 345
//3 becomes unit, 4 becomes 10 and 5 becomes 100th
//Basically reversing the place value;
int pv = count;
int rem =0;
int newPlaceValue;
int rev= 0;
while(pv>=0 && orig>=0)
{

rem = orig%10;
rev = rev + (rem*pow(10, pv));
orig=orig/10;
pv--;

}
return rev=rev/10;

}
int main()
{
int n;
cin>>n;
int answer = reverse(n);
cout << answer;
}

Okay, so you might be wondering why this big chunk of code just to reverse a number... why not the regular conservative way to do it... Basically I want to show that mugging up and writting/copying things is a waste of time..Enuf of the pep talk lets get into the solution description......
You need to have knowledge about place values of a given number....if you see all you are doing is reversing the place values backwards therefore do so.......
`

Top comments (0)

Do you have your sticker pack yet?