DEV Community

Discussion on: Daily Coding Puzzles - Oct 29th - Nov 2nd

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Thank you, Ali.
This has been one of the most fun challenges.

Took me awhile but here is the C# version.

The gist is that, remainder is calculated for each digit, stored in a stack (LIFO - last in first out) to reverse the remainder.

Lastly the total is reconstructed from the stack.

Runnable code on .NET Fiddle

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var a = new int[] {123456, 5, 654321, 1234567890};

        foreach (var n in a) {
            Console.WriteLine($"Reversed = {Reverse(n)}");  
        }
    }

    private static int Reverse(int input) {
        var stack = BuildStack(input);
        return ConvertStackToNumber(stack);
    }

    private static Stack<int> BuildStack(int input) {
        var power = 0;
        var stack = new Stack<int>();

        while (true) {
            power++;
            var modBy = (int) Math.Pow(10, power);
            var divisior = (int) Math.Pow(10, power - 1);

            var remainder = (input % modBy) / divisior;
            if (remainder == 0 && power != 1) break;

            stack.Push(remainder);
        }
        return stack;
    }

    private static int ConvertStackToNumber(Stack<int> stack) {
        var total = 0;
        var power = 0;
        while (stack.Count > 0) {
            var current = stack.Pop();
            total += current * (int)Math.Pow(10, power++);
        }
        return total;
    }
}
Collapse
 
aspittel profile image
Ali Spittel

Oh that's a really cool approach!