2016-10-09 5 views
0

Ich möchte für das Programm durch jede mögliche Binärzahl von 00000000 bis 11111111 I durchlaufen und I, um die Anzahl der aufeinanderfolgenden "Läufe" von Einsen zu berechnen. Ex) 00000001 und 11100000 beide zählen als ein einzelnen Läufe von Einsen 00001010 und 11101110 beide zählen als zwei Läufe von EinsenBerechnung der Anzahl der aufeinander folgenden in einer Binärzahl mit C#

Das Problem ist, ist, dass es das ignoriert und ein Teil Maske und ich weiß nicht, warum.

{ 
    static void Main(string[] args) 
    { 
     //Start 
     int stuff = BitRunner8(); 

     //Display 
     Console.Write(stuff); 
     Console.ReadKey(); 
    } 
    public static int BitRunner8() 
    { 
     int uniRunOrNot = 0; 
     int uniRunCount = 0; 
     int uniRunTotal = 0; 

     //iterating from numbers 0 to 255 
     for (int x = 0; x < 255; x++) 
     { 
      //I use 128 as my AND mask because 128 is 10000000 in binary 
      for (int uniMask = 128; uniMask != 0; uniMask >>= 1) 
      { 

       //This is the if statement that doesn't return true ever 
       if ((x & uniMask) != 0) 

       { 
        //If the and mask is true, and ther were no previous ones before it, add to the the uniRunCount 
        if (uniRunOrNot == 0) 
        { 
         //Total count of the runs 
         uniRunCount++; 
        } 
        // Making it so that if two consective ones are in a row, the 'if' statement right above would return false, 
        //so that it wouldn't add to the uniRunCount 
        uniRunOrNot++; 
       } 
       else 
       { 
        //add the total number of runs to uniRunTotal, and then reset both uniRunOrNot, and uniRunCount 
        uniRunTotal += uniRunCount; 
        uniRunOrNot = uniRunCount = 0; 
       } 
      } 
     } 
     //Divide the final amount by 256 total numbers 
     uniRunTotal /= 256; 
     return uniRunCount; 
    } 
} 

Antwort

0

Das Problem ist, dass Ihr Code Läufe ignoriert, die das niedrigstwertige Bit enthalten. Ihr Code aktualisiert uniRunTotal nur, wenn es ein Null-Bit entdeckt. Wenn das niedrigstwertige Bit ungleich Null ist, wird uniRunCount niemals zum Gesamtwert hinzugefügt.

Fügen Sie Code nach der Schleife hinzu, um uniRunCount hinzuzufügen, um dieses Problem zu beheben.

Sie dieses Problem auch durch Anlegen einer Sentinel Strategie beheben: Bits vom anderen Ende zählen, und neun Bits anstelle von acht, weil Bit-Zahl neun ist immer Null:

for (int uniMask = 1; uniMask <= 256; uniMask <<= 1) 
Verwandte Themen