I need the code in console Applecation

Dani AI

Generated

A compact, robust console example that uses a Stack and accepts arbitrary-size integers. This complements 's posted approach and the resource pointed to, while adding input validation, correct handling for zero and negative numbers, and support for very large values via BigInteger.

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

class Program
{
    static void Main()
    {
        Console.Write("Enter an integer: ");
        string input = Console.ReadLine()?.Trim();
        if (!BigInteger.TryParse(input, out BigInteger n))
        {
            Console.WriteLine("Invalid integer.");
            return;
        }

        if (n.IsZero)
        {
            Console.WriteLine("0 in binary is 0");
            return;
        }

        bool negative = n.Sign < 0;
        n = BigInteger.Abs(n);

        var bits = new Stack<int>();
        while (n > 0)
        {
            bits.Push((int)(n % 2));
            n /= 2;
        }

        var sb = new StringBuilder();
        if (negative) sb.Append('-');
        while (bits.Count > 0) sb.Append(bits.Pop());

        Console.WriteLine("{0} in binary is {1}", input, sb.ToString());
    }
}

How it works: parse the input (with validation), treat zero as a special case, record the sign, then repeatedly push remainders (n % 2) onto the Stack. Popping produces the binary digits in the correct order without extra reversing. This keeps the stack-focused logic clear for learning purposes.

Notes/troubleshooting: add using System.Numerics and ensure your project targets .NET 4.0+ (or reference System.Numerics.dll) to use BigInteger. If you only need 64-bit integers, replace BigInteger.TryParse with long.TryParse and operate on ulong for the absolute value (watch out for long.MinValue). For a quick one-liner on small ints you can use built-in conversions, but for learning stack behavior the manual method above is preferred.

Recommended Answers

All 2 Replies

Check here:

using System;
using System.Collections.Generic;
using System.Text;

namespace TestBed {
    class TestBed {
        static void Main() {
            Stack<int> myStack = new Stack<int>();
            decimal d = 4234234234234;

            decimal t = d;
            while (t > 0) {
                int r = (int)(t % 2);
                myStack.Push(r);
                t = Math.Floor(t/2);
            }

            StringBuilder sb = new StringBuilder();
            while (myStack.Count > 0) {
                sb.Append(myStack.Pop());
            }

            Console.WriteLine("{0} in binary is {1}", d, sb.ToString());

            Console.ReadLine();

        }
    }
}

I sure hope I get an A on this assignment!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.