Reverse Integer

By   Tewodros   Date Posted: Feb. 19, 2022  Hits: 745   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given an integer number n, we want to reverse its digits. We are not allowed to use extra memory like arrays to do this. We have to do it only using antiemetics. 

Example:

n = 123      

Ans: 321

Solution:

We want to make sure we handle negative integers first. To do that we just multiply the number by -1 to make it positive. 

The trick here is to understand the formula here 

  reverse = (reverse * 10) + (n%10);   where reverse = 0 initially and it got the new value every time we divide n by 10

 

   public int Reverse(int x) {        

       long reverse = 0;       

       long n = (x<0)? -1*x: x;

       while(n > 0)     {

           rev = (reverse * 10) + (n%10);

           n/=10;

       }   

       if(reverse > Int32.MaxValue)

           return 0;   

    return (x<0)? (int)(-1*rev): (int)reverse ;

}


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* slzwqi

Back to Top