Quick actions

cmd+k|ctrl+k

Navigation

Languages

Udemy: Master Coding Interview - Recursion - #159

Snippet info

Language

Csharp

Visibility

public

Author

jcurrie33

Created

2020-08-12T06:42:43Z

Updated

2020-08-12T06:42:43Z

using System;

//Implement a function that reverses a string using iteration...
//and then recursion!
class MainClass {
    static void Main() {
        Console.WriteLine("Hello World!");
        Console.WriteLine("ReverseIterative('yoyo mastery') = " 
        + ReverseIterative("yoyo mastery"));
        Console.WriteLine("ReverseRecursive('yoyo mastery') = " 
        + ReverseRecursive("yoyo mastery"));
    }
    
    public static string ReverseIterative(string s) {
        char[] c = s.ToCharArray();
        char[] c2 = new char[c.Length];
        for (int i = 0; i < c.Length; i++) {
            c2[c.Length-1-i] = c[i];
        }
        string s2 = new string(c2);
        return s2;
    }
    
    public static string ReverseRecursive(string s) {
        if (s.Length == 1) {
            return s;
        } else {
            return s.Substring(s.Length-1,1) 
            + ReverseRecursive(s.Substring(0,s.Length-1));
        }
    }
}
INFO