/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package plaindromenumbers;
import java.util.Scanner;
/**
*
* @author taha
*/
public class PlaindromeNumbers {
/**
* @param args the command line arguments
*/
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
-
2You forgot to ask a question, but neat code dump.CollinD– CollinD2017-03-19 18:18:22 +00:00Commented Mar 19, 2017 at 18:18
-
If you're getting a stack overflow error, your recursion is too deep. Either you have a code bug, or you need to redo this so it doesn't use recursion.D M– D M2017-03-19 18:19:27 +00:00Commented Mar 19, 2017 at 18:19
-
As a side note, don't explicitly compare to true and false.EJoshuaS - Stand with Ukraine– EJoshuaS - Stand with Ukraine2017-03-19 18:27:51 +00:00Commented Mar 19, 2017 at 18:27
2 Answers
Here is the problem:
func(no++);
Let's say no is 32. This will pass 32 to func and then increment it. Which means that you are once again calling the function with a value of 32. And when that function hits this line, it will, once again, pass that 32 to func. Hence, an infinite recursive loop.
You can fix this bug like this:
func(++no);
Now it will increase no before calling func. no will be 33, it will match its reverse, and all will be well.
3 Comments
You will need to return func(no + 1), this way your code will return the next palindrome number (which I assume is what you want your code to do?). check is not needed. Why include func1 when it's not even used by your code?
By the way, the stack overflow is caused by the infinite recursion of func.