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.
total
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; } }
Oh that's a really cool approach!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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
Oh that's a really cool approach!