Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // package whatever; // don't place package name!
- import java.io.*;
- /**
- * 2c. Reverse a string using Helper Method Recursion
- *
- * Input: String
- * Output: String
- *
- * Example: String greeting = 'hello';
- * ReverseString.compute(greeting) => 'olleh'
- */
- class ReverseString {
- public static void main (String[] args) {
- String str = "hello";
- System.out.println(compute(str));
- }
- public static String compute(String str) {
- //if string is empty or contains 1 character, return string
- if(str.length() <=1 ){
- return str;
- }
- //to help w/visualization of recursive call
- System.out.println(str.substring(1));
- //substring returns string from element 1 - string.length()
- return compute(str.substring(1)) + str.charAt(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement