Created
September 20, 2017 11:00
-
-
Save javamultiplex/3043b6ee8089874cc5830703a9dfb40a to your computer and use it in GitHub Desktop.
Reverse of String using Recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.string; | |
import java.util.Scanner; | |
/** | |
* @author Rohit Agarwal | |
* @category String Interview Questions | |
* @problem Reverse String using Recursion method | |
* | |
*/ | |
public class ReversedStringByRecursion { | |
public static void main(String[] args) { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter String :"); | |
String string = input.nextLine(); | |
int length = string.length(); | |
String newString = getReverseString(string, length); | |
System.out.println("Reversed String is :\n" + newString); | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static String getReverseString(String string, int length) { | |
if (length == 1) { | |
// Converting char to String. | |
return String.valueOf(string.charAt(0)); | |
} else | |
return string.charAt(length - 1) + getReverseString(string, length - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment