re: Daily Coding Puzzles - Oct 29th - Nov 2nd VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Wednesday Write a program to reverse the digits of a positive integer but without converting it to a string.
 

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;
    }
}
 
code of conduct - report abuse