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.......
`

Oldest comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesnโ€™t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.