Sunday 17 July 2016

Reverse integer

/*  Reverse integer */
/*
    Reverse digits of an integer.
    Example1: x = 123, return 321
    Example2: x = -123, return -321
    Return 0 if the result overflows and does not fit in a 32 bit signed integer
    Overflow detection : Make sure when there's an operation that increase a number, reverse that
    operation and it should have the previous number. Otherwise there's overflow.
*/

 #include<iostream>  
 #include<cmath>  
 using namespace std;  
 int reverse(int x) {  
   int t = x;  
   x = abs(x);  
   int reversed = 0;  
   int y;  
   while(x > 0){  
     y = reversed;  
     reversed = 10 * reversed + x % 10;  
     //reverse the operation and it should have the previous number  
     if((reversed - x % 10) / 10 != y)  
       return 0;  
     x = x / 10;  
   }  
   if(t < 0)  
     reversed = - 1 * reversed;  
   return reversed;  
 }  
 int main(){  
   cout << reverse(1235463567);  
   return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive