C# :: Aufgabe #231

5 Lösungen Lösungen öffentlich

Binärzahlen ohne Doppelnull

Anfänger - C# von hollst - 20.11.2018 um 09:55 Uhr
Es sein z. B. N = 10.000.

Man schreibe ein Programm, das alle natürlichen Zahlen kleiner N auflistet,
die in ihrer binären Repräsentation keine zwei aufeinander folgende Nullen besitzen.

Anmerkung: Führende Nullen werden nicht berücksichtigt, die erste natürliche Zahl, die nicht in der Liste wäre,
ist somit die 4 (4-dezimal = 100-binär).

Viel Spaß!

Lösungen:

vote_ok
von Exception (7090 Punkte) - 26.11.2018 um 20:19 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinaerDoppelteNull_231
{
    class Program
    {
        
        private static int n;

        static void Main(string[] args)
        {
            Dictionary<int, string> mapping = new Dictionary<int, string>();

            try
            {
                if(args.Length != 1)
                {
                    throw new ArgumentException("Es muss ein Ganzzahl Parameter übergeben werden.");
                }
                if (!int.TryParse(args[0], out n))
                {
                    throw new Exception("Fehlerhafte Eingabe \"" + args[0] + "\"");
                }
                if(n < 1)
                {
                    throw new ArgumentException("N muss größer oder gleich 1 sein.");
                }

                Console.WriteLine("n = {0}", n);
                Console.WriteLine("-------------------------");
                Console.WriteLine("Liste alle Zahlen auf, die keine zwei Nullen (Binärdarstellung) hintereinander enthalten...");
                Console.WriteLine();

                mapping = getDecBinMapping();

                printValues(mapping);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }

            Console.ReadLine();
        }

        private static Dictionary<int, string> getDecBinMapping()
        {
            Dictionary<int, string> mapping = new Dictionary<int, string>();

            for (int currentDecimal = 0; currentDecimal < n; currentDecimal++)
            {
                string binaryValue = Convert.ToString(currentDecimal, 2);

                if(!binaryValue.Contains("00"))
                {
                    mapping.Add(currentDecimal, binaryValue);
                }
            }

            return mapping;
        }

        private static void printValues(Dictionary<int, string> mapping)
        {
            Console.WriteLine("Dezimal\t\tBinär");
            Console.WriteLine("-------------------------");

            foreach (KeyValuePair<int, string> pair in mapping)
            {
                Console.WriteLine("{0}\t\t{1}", pair.Key, pair.Value);
            }

            Console.WriteLine("-------------------------");
            Console.WriteLine("Es wurden von {0} Binärzahlen {1} ohne Doppelnull gefunden.", n, mapping.Count);
        }
    }
}

vote_ok
von RevTreb (860 Punkte) - 27.11.2018 um 16:00 Uhr
Quellcode ausblenden C#-Code
using System;

namespace BitMaskFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            
            for (int i = 1; i < 10000; i++)
                if (Test(i))
                    Console.WriteLine(string.Format("{0}\t{1}", i, Convert.ToString(i, 2)));
            Console.ReadLine();
        }

        static bool Test(int i)
        {
            string binary = Convert.ToString(i, 2);
            int actpos = 0;
            bool found = false;
            while (actpos<binary.Length)
            {
                if (binary[actpos] == '0')
                    if (binary.Length>actpos+1)
                        if (binary[actpos + 1] == '0')
                        {
                            found = true;
                            break;
                        }
                actpos++;        
            }           
            return !found;
        }
    }
}
vote_ok
von Philipp (160 Punkte) - 08.12.2018 um 18:27 Uhr
Quellcode ausblenden C#-Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Text.RegularExpressions;

namespace ConsoleApp31
{
    class Program
    {
        static void Main(string[] args)
        {
            berechnung();
            Console.ReadLine();
        }

      

        public static void berechnung()
        {
            Console.WriteLine("Bitte gewünschte dezimalzahl eingeben, die größer als 0 ist");
            int eingabe = Convert.ToInt32(Console.ReadLine());

           
            int i = 1;
            

            

            while(i <= eingabe)
            {
                string binary = Convert.ToString(i, 2);
               

                string pattern = "100";
                Match match = Regex.Match(binary, pattern);
                
                if(match.Success)
                {
                   
                    i++;
                    continue;
                }
                else
                {
                    int binaryAusgabe = Convert.ToInt32(binary, 2);
                    Console.WriteLine(binaryAusgabe);
                    i++;  
                }
            }           
        }
    }
}
vote_ok
von AchtungHuPe (170 Punkte) - 03.01.2019 um 17:38 Uhr
* Anmerkungen:
* 1. Führende Nullen werden nicht berücksichtigt (die erste natürliche Zahl nicht in der Liste ist somit 4 (100)
* 2. N wird auf 2^8 limitiert. Dies ist eine willkürliche Einschränkung der Aufgabenstellung
* 3. Die Zahl 0 wird hier dem Zahlenraum der natürlichen Zahlen zugeschlagen

Quellcode ausblenden C#-Code
using System;

namespace Decimal2Binary
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Gib eine positive Ganzzahl bis 255 ein: ");
            string inputN = Console.ReadLine();

            byte n = 0;
            if (!byte.TryParse(inputN, out n))
            {
                Console.WriteLine("Zahl ungültig oder keine Zahl. Beenden mit beliebiger Taste.");
                Console.ReadKey();
            }
            else
            {
                for (int i = 0; i <= n; i++)
                {
                    string binary = Convert.ToString(i, 2);
                    bool isNullNull = false;

                    for (int j = 1; j < binary.Length; j++)
                    {
                        if (binary.Substring(j, 1) == "0" && binary.Substring(j - 1, 1) == "0")
                        {
                            isNullNull = true;
                            break;
                        }
                    }

                    if (!isNullNull)
                    {
                        Console.WriteLine("{0} hat in seiner Binärrepräsentation ({1}) kein zwei aufeinanderfolgende 0er.", i, binary);
                    }
                }
            }

            Console.WriteLine("\nFertig, beenden mit beliebiger Taste."); Console.ReadKey();
        }
    }
}
1 Kommentar
vote_ok
von hollst (13980 Punkte) - 18.07.2019 um 18:26 Uhr
Quellcode ausblenden C#-Code
using static System.Console;
using System.Collections.Generic;
using System.Text;

namespace Aufgabe_231
{
    static class Program
    {
        static void Main()
        {
            List<int> result = new List<int>();
            int nmax = (int)1E+4;
            for(var i = 1; i < nmax; i++)
            {
                int[] temp = i.DecToBin();
                if (temp.CheckDoubleNull())
                {
                    result.Add(i);
                    WriteLine($"{i.ToString("n0"),10}: {temp.ToMyString()}");
                }
            }
            WriteLine($"{result.Count.ToString("n0")} items in list");       
            ReadKey();
        }
        static int[] DecToBin(this int n)
        {
            List<int> temp = new List<int>();
            while(n > 0)
            {
                temp.Add(n % 2);
                n /= 2;
            }
            return temp.ToArray();
        }

        static string ToMyString(this int[] n)
        {
            StringBuilder sb = new StringBuilder();
            for (var i = 0; i < n.Length; i++)
                sb.Append($"{n[i],4}");
            return sb.ToString();
        }

        static bool CheckDoubleNull(this int[] n)
        {
            int inull = 0;
            for(var i = 0; i < n.Length; i++)
            {
                if (n[i] == 0)
                    inull++;
                else
                    inull--;
                if (inull == 2)
                    return false;
            }
            return true;
        }
    }
}
1810283

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.