I am new to java. I was just writing a function to accept a number and its base as argument and then show the palindrome number (if any). The main problem is that I don't exactly get it how to reverse the number of base other than 10? The Code I wrote (according to my poor logic ) is below:
void CheckPalidrome( int num, int base)
{
long n=num;
boolean palid=false;
long TNum= num;
for(int i=1; i<=10 && palid==false; ++i)
{
int rev=0;
while(n>0 )
{
int d= (int) (n%base);
rev= rev*base + d;
n/=base;
}
if(TNum==rev)
{
palid=true;
}
else{
n=TNum+rev;
TNum=n;
}
System.out.println("TNum= "+TNum+"\trev="+rev);
}
if(palid==true){
System.out.println("Palidrome= "+TNum);
}
else{
System.out.println("None, "+TNum);
}
}
But, there is a problem in this. It works fine for any number of base 10. But doesn't work for another base. For example:- 87 with base 10 will be reversed and checked if it is a Palindrome, if not it the reverse and number will be added and checked again Just Like: 87+78= 165+ 561 = 726 + 627= 1353 + 3531 = Palindrome !
But I don't know how to do this for other bases except 10. Note: 1211 with base 3 forms Palindrome 112211 and 3112 with base 4 forms Palindrome 233332 . I used these results to test my code. But the output doesn't match.
Please forgive my poor English. Kindly share your knowledge or give me any idea to solve the problem. I shall be glad and thankful to you :)
Your logic seems to be good, but remember to parse and print numbers in the given base
.
E.g. the number 1211
(base 3) is the same as 49
(base 10).
To see this, I rewrote your code like this:
private static int findPalindrome(int num, int base) {
for (int n = num, rev; n > 0; n += rev) {
if ((rev = reverse(n, base)) == n)
return n;
System.out.printf("%-6s + %-6s", Integer.toString(n, base), Integer.toString(rev, base));
if (base != 10)
System.out.printf(" = (%-4d + %-4d) ", n, rev);
System.out.printf("%n = ");
}
return 0;
}
private static int reverse(int num, int base) {
int rev = 0;
for (int n = num; n != 0; n /= base)
rev = rev * base + n % base;
return rev;
}
Then tested it like this:
public static void main(String[] args) {
test("87", 10);
test("1211", 3);
test("3112", 4);
}
private static void test(String num, int base) {
System.out.printf("%2d: ", base);
int p = findPalindrome(Integer.parseInt(num, base), base);
System.out.printf("%-15s", Integer.toString(p, base));
if (base != 10)
System.out.printf(" = (%-11d)", p);
System.out.printf("%n%n");
}
Which produced this output:
10: 87 + 78
= 165 + 561
= 726 + 627
= 1353 + 3531
= 4884
3: 1211 + 1121 = (49 + 43 )
= 10102 + 20101 = (92 + 172 )
= 100210 + 12001 = (264 + 136 )
= 112211 = (400 )
4: 3112 + 2113 = (214 + 151 )
= 11231 + 13211 = (365 + 485 )
= 31102 + 20113 = (850 + 535 )
= 111221 + 122111 = (1385 + 1685)
= 233332 = (3070 )
The numbers in ()
are the base 10 numbers. The other numbers are shown in the base
listed before the :
.