Advertisement
gelita

Reverse a string using Helper Method Recursion

Feb 10th, 2020
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.82 KB | None | 0 0
  1. // package whatever; // don't place package name!
  2.  
  3. import java.io.*;
  4. /**
  5.  *  2c. Reverse a string using Helper Method Recursion
  6.  *
  7.  *  Input:   String
  8.  *  Output:  String
  9.  *
  10.  *  Example: String greeting = 'hello';
  11.  *          ReverseString.compute(greeting) => 'olleh'
  12.  */
  13. class ReverseString {
  14.  
  15.     public static void main (String[] args) {
  16.      String str = "hello";
  17.      System.out.println(compute(str));
  18.       }
  19.  
  20.     public static String compute(String str) {
  21.       //if string is empty or contains 1 character, return string
  22.       if(str.length() <=1 ){
  23.         return str;
  24.       }
  25.       //to help w/visualization of recursive call
  26.       System.out.println(str.substring(1));
  27.       //substring returns string from element 1 - string.length()
  28.       return compute(str.substring(1)) + str.charAt(0);
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement