Results 1 to 2 of 2
Thread: recursive method problem
- 10-29-2009, 12:04 AM #1
Member
- Join Date
- Oct 2009
- Posts
- 3
- Rep Power
- 0
recursive method problem
a) What is the output of the following recursive code?
public static void main(String[] args){
System.out.println(foo(4));
}
public static int foo(int n){
System.out.println(n);
if (n == 0)
return n;
else
return n + foo(n - 1);
}
b) Write a recursive method that accepts a single String as a parameter and returns ther reverse of that String. For example, calling the method reverse("Test")would return the String "tseT."
My answer is these? are those right? thank you
(a)
4
3
2
1
0
10
(b)
public static String reverse(String str) {
if (str == null || str.length() == 0)
return null;
else if (str.length() == 1) {
return str;
} else
return str.charAt(str.length() - 1)+reverse(str.substring(0, str.length() - 1));
}
- 10-29-2009, 08:15 AM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 14
Similar Threads
-
Recursive method using int array, help needed
By chupalo17 in forum New To JavaReplies: 4Last Post: 09-08-2009, 12:15 AM -
Java Recursive method problem
By kj2009 in forum Advanced JavaReplies: 2Last Post: 02-25-2009, 04:19 PM -
exercise of recursive method
By amexudo in forum New To JavaReplies: 2Last Post: 03-09-2008, 06:55 PM -
Recursive Method ==> find minimum value from array
By NatNat in forum New To JavaReplies: 1Last Post: 02-16-2008, 10:10 PM -
Recursive Method
By bluegreen7hi in forum New To JavaReplies: 5Last Post: 11-29-2007, 05:45 AM
Bookmarks