Skip to content

Instantly share code, notes, and snippets.

@deyindra
Created April 13, 2017 21:45
Show Gist options
  • Select an option

  • Save deyindra/ca4dea637c6de2ee20a22a9d437bc2be to your computer and use it in GitHub Desktop.

Select an option

Save deyindra/ca4dea637c6de2ee20a22a9d437bc2be to your computer and use it in GitHub Desktop.
Planidromic Number
/**
* Calculate how many palindromic n-digit numbers are present
* for 2 digit the palindromic numbers are 11, 22, 33, 44, 55, 66, 77, 88, 99 (total of 9)
**/
public static int numberOfPalindromicProblem(int n){
if((n & 1) != 0){
n = n/2;
}else{
n = n/2 -1;
}
return (int)(9 * Math.pow(10,n));
}
/**
* Calculate nth Palindromic number of k digit, e.g. 1st Palindromic number in 3 digit is 101
**/
public static int printPalinDromeNumber(int n, int k){
if(k<=0){
throw new IllegalArgumentException("Invalid value of "+k);
}
int totalNumberOfPalinDromicNumber = numberOfPalindromicProblem(k);
if(n<1 || n>totalNumberOfPalinDromicNumber){
throw new IllegalArgumentException("Nth digit should be range between 1 and "+totalNumberOfPalinDromicNumber);
}
int temp = (k & 1) !=0 ? k/2 : k/2 -1;
int palindrome = (int)Math.pow(10, temp);
palindrome += n - 1;
int actualNumber = palindrome;
if ((k & 1)!=0)
palindrome /= 10;
while (palindrome!=0)
{
actualNumber = actualNumber*10 + palindrome % 10;
palindrome /= 10;
}
return actualNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment