Reverse a number

Algorithm for reversing the number is as follows:

#include <cmath> // for finding out the length of number
// find the length of the number to find out the highest power of 10
// then divide the number by 10 and take remainder to find digit 
// at the unit's place.
// multiply the digit with power of 10. repeat length times.
int reverse(int x) {
  int length = (int)log10(abs(x)); // magic formula to find length
  int reversed = 0;
  int remainder = 0;
  for(int i = length; i > 0 ; --i){
    remainder = x % 10;
    x = x / 10;
    reversed += remainder * pow(10, i);
  reversed += x;
  return reversed;


Author: Saurabh Purnaye

VP - Low Latency Developer @jpmchase... Linux, C++, Python, Ruby. pursuing certificate in #QuantFinance and Passed CFA L1

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: