Friday, June 2, 2017

Palindrome Number


Problem statement

Determine whether an integer is a palindrome. Do this without extra space.

Link to GitHub :Code 

Example
Input 12321 is a palindrome number
Input 1231 is not a palindrome number





Solution

  • We need 2 variables x and rev.
  • Initialize rev to 0 and keep adding multiplication of 10 modulus(Remainder) of  of x. The result would be it would getting integer in reverse order ex: 12
  • Keep dividing x with 10  and the result would be x would keeping loosing one integer value from the end
  • This loop would continue till x > rev
  • In the return statement we need to check if  x is equal to reverse or x is equal to rev/ 10
public static boolean get(int x)
	{
		if (x<0 || (x!=0 && x%10==0)) return false;
	    int rev = 0;
	    while (x>rev){
	      //Input 12321
	       //0 = 0 + 1
	       //1 = 10+ 2
	       //12= 120+3 =123
	       	rev = rev*10 + x%10;
	       	//1232
	       	//123
	       	//12
	       	x = x/10;
	    }
	    return (x==rev || x==rev/10);
	}

Iteration


No comments:

Post a Comment