Language – Java | Type – Problem (Code) | Last date 08-Apr-2009 9:00 p.m. IST | Points 5
My little brother (a charming character usually) came to me the other day and said, “Don’t you think this pattern is amazing. I bet you computer folks could never make something like this”. “Ha” I scoffed “that’s simple recursion”. Simple recursion – was I out of my mind – when did recursion become simple? So here I am folks stuck on another problem. Any help?
When n = 1; output 1
When n = 2; output 121
When n = 3; output 1213121
When n = 4; output 121312141213121
Program must work for all positive integers ‘n’
Got an answer? Why don’t you leave it here.
import java.io.*;
ReplyDeleteclass FunnyExercise {
public static void main(String[] args) {
Console console = System.console();
System.out.print("Enter the desired number : ");
int input = Integer.parseInt(console.readLine());
String result = getText(input);
System.out.print("Answer is : "+result);
}
private static String getText(int n) {
String text = "";
if(n == 1) {
text = "1";
return text;
}
String txt = printText(n-1);
String retVal = txt+String.valueOf(n)+txt;
return retVal;
}
}