Quick actions

cmd+k|ctrl+k

Navigation

Languages

Reverse

Snippet info

Language

Java

Visibility

public

Author

ingserge

Created

2024-10-13T06:44:26.367992Z

Updated

2024-10-14T22:58:54.749053Z

class Main {
    
    public static String reverseIterative(String string){
        String reversedString="";
        
        for (int i=0; i < string.length(); i++){
            reversedString += string.charAt(string.length()-1-i);
        }
        return reversedString;
    }
    
    public static String reverseRecursive(String string){
        if (string == null || string.isEmpty()){
            System.out.println("Empty string cannot be reversed.");
            return "";
        }
        
        return reverseRecursive(string, string.length()-1);
        
    }
    
    public static String reverseRecursive(String string, int index){
        if (index == 0){
            return ""+string.charAt(0);
        }
        return ""+string.charAt(index)+reverseRecursive(string, index-1);
    }
    
    public static void main(String[] args) {
        System.out.println("ReverseIterative: "+reverseIterative("unodos"));
        System.out.println("ReverseRecursive: "+reverseRecursive("unodos"));
    }
}
INFO