Cel mai lung 1 consecutiv în reprezentarea binară

Dat un număr n Sarcina este de a găsi lungimea celui mai lung consecutiv 1s serie în reprezentarea sa binară.
Exemple:  

Intrare: n = 14
Ieșire: 3
Explicaţie: Reprezentarea binară a lui 14 este 111 0.

Intrare: n = 222
Ieșire: 4
Explicaţie:  Reprezentarea binară a lui 222 este 110 1111 0.

Cuprins

[Abordare naivă] Timpul iterativ O(1) și spațiul O(1)

C++
   #include          using     namespace     std  ;   int     maxConsecutiveOne  (  int     n     ){          int     count     =     0     ;      int     maxi     =     0     ;      // traverse and check if bit set increment the count      for     (  int     i     =     0     ;     i      <     32     ;     i  ++  ){      if     (  n     &     (  1      < <     i  )){      count  ++  ;      }     else     {      maxi     =     max     (  maxi          count  );      count     =     0     ;      }      }      return     maxi  ;   }   int     main  ()     {      int     n     =     14     ;      cout      < <     maxConsecutiveOne  (  n  )      < <  'n'  ;      return     0  ;   }   
Java
   public     class   GFG     {      static     int     maxConsecutiveOne  (  int     n  )     {      int     count     =     0  ;      int     maxi     =     0  ;      // traverse and check if bit set increment the count      for     (  int     i     =     0  ;     i      <     32  ;     i  ++  )     {      if     ((  n     &     (  1      < <     i  ))     !=     0  )     {      count  ++  ;      }     else     {      maxi     =     Math  .  max  (  maxi       count  );      count     =     0  ;      }      }      return     maxi  ;      }      public     static     void     main  (  String  []     args  )     {      int     n     =     14  ;      System  .  out  .  println  (  maxConsecutiveOne  (  n  ));      }   }   
Python
   def   maxConsecutiveOne  (  n  ):   count   =   0   maxi   =   0   # traverse and check if bit set increment the count   for   i   in   range  (  32  ):   if   n   &   (  1    < <   i  ):   count   +=   1   else  :   maxi   =   max  (  maxi     count  )   count   =   0   return   maxi   if   __name__   ==   '__main__'  :   n   =   14   print  (  maxConsecutiveOne  (  n  ))   
C#
   using     System  ;   class     GFG   {      static     int     MaxConsecutiveOne  (  int     n  )      {      int     count     =     0  ;      int     maxi     =     0  ;      // traverse and check if bit set increment the count      for     (  int     i     =     0  ;     i      <     32  ;     i  ++  )      {      if     ((  n     &     (  1      < <     i  ))     !=     0  )      {      count  ++  ;      }      else      {      maxi     =     Math  .  Max  (  maxi       count  );      count     =     0  ;      }      }      return     maxi  ;      }      static     void     Main  ()      {      int     n     =     14  ;      Console  .  WriteLine  (  MaxConsecutiveOne  (  n  ));      }   }   
JavaScript
   function     maxConsecutiveOne  (  n  )     {      let     count     =     0  ;      let     maxi     =     0  ;      // traverse and check if bit set increment the count      for     (  let     i     =     0  ;     i      <     32  ;     i  ++  )     {      if     (  n     &     (  1      < <     i  ))     {      count  ++  ;      }     else     {      maxi     =     Math  .  max  (  maxi       count  );      count     =     0  ;      }      }      return     maxi  ;   }   // Driver code   let     n     =     14  ;   console  .  log  (  maxConsecutiveOne  (  n  ));   

Ieșire
3  

[Abordare eficientă] Folosind manipularea biților O(1) Timp și O(1) spațiu

Ideea se bazează pe conceptul că ŞI de secvență de biți cu a stânga deplasat cu 1 versiunea de sine elimină efectiv trailing-ul 1 din fiecare succesiune de consecutive 1s .  

Deci operația n = (n & (n < < 1)) reduce lungimea fiecărei secvențe de 1s de unul în reprezentare binară a n . Dacă continuăm să facem această operație într-o buclă cu care ajungem n = 0. Numărul de iterații necesare pentru a ajunge este de fapt lungimea celei mai lungi secvente consecutive de 1s .

Ilustrare:


Urmați pașii de mai jos pentru a implementa abordarea de mai sus:

  • Creați un număr de variabile inițializate cu valoare .
  • Rulați o buclă while până n nu este 0.
    • În fiecare iterație efectuați operația n = (n & (n < < 1))
    • Creșteți numărul cu unu.
  • Număr de întoarceri
C++
   #include       using     namespace     std  ;   int     maxConsecutiveOnes  (  int     x  )   {      // Initialize result      int     count     =     0  ;      // Count the number of iterations to      // reach x = 0.      while     (  x  !=  0  )      {      // This operation reduces length      // of every sequence of 1s by one.      x     =     (  x     &     (  x      < <     1  ));      count  ++  ;      }      return     count  ;   }   int     main  ()   {      // Function Call      cout      < <     maxConsecutiveOnes  (  14  )      < <     endl  ;      return     0  ;   }   
Java
   class   GFG   {      private     static     int     maxConsecutiveOnes  (  int     x  )      {      // Initialize result      int     count     =     0  ;      // Count the number of iterations to      // reach x = 0.      while     (  x  !=  0  )      {      // This operation reduces length      // of every sequence of 1s by one.      x     =     (  x     &     (  x      < <     1  ));      count  ++  ;      }      return     count  ;      }      public     static     void     main  (  String     strings  []  )      {      System  .  out  .  println  (  maxConsecutiveOnes  (  14  ));      }   }   
Python
   def   maxConsecutiveOnes  (  x  ):   # Initialize result   count   =   0   # Count the number of iterations to   # reach x = 0.   while   (  x  !=  0  ):   # This operation reduces length   # of every sequence of 1s by one.   x   =   (  x   &   (  x    < <   1  ))   count  =  count  +  1   return   count   if   __name__   ==   '__main__'  :   print  (  maxConsecutiveOnes  (  14  ))   # by Anant Agarwal.   
C#
   using     System  ;   class     GFG     {          // Function to find length of the       // longest consecutive 1s in binary      // representation of a number       private     static     int     maxConsecutiveOnes  (  int     x  )      {          // Initialize result      int     count     =     0  ;      // Count the number of iterations      // to reach x = 0.      while     (  x     !=     0  )      {          // This operation reduces length      // of every sequence of 1s by one.      x     =     (  x     &     (  x      < <     1  ));      count  ++  ;      }      return     count  ;      }      // Driver code      public     static     void     Main  ()      {      Console  .  WriteLine  (  maxConsecutiveOnes  (  14  ));      }   }   // This code is contributed by Nitin Mittal.   
JavaScript
   function     maxConsecutiveOnes  (  x  )     {      // Initialize result      let     count     =     0  ;      // Count the number of iterations to reach x = 0      while     (  x     !==     0  )     {          // This operation reduces length of       // every sequence of 1s by one      x     =     (  x     &     (  x      < <     1  ));      count  ++  ;      }      return     count  ;   }   // Driver code   console  .  log  (  maxConsecutiveOnes  (  14  ));   
PHP
      // PHP program to find length    function   maxConsecutiveOnes  (  $n  )   {   // Initialize result   $count   =   0  ;   // Count the number of    // iterations to reach x = 0.   while   (  $n   !=   0  )   {   // This operation reduces    // length of every sequence   // of 1s by one.   $n   =   (  $n   &   (  $n    < <   1  ));   $count  ++  ;   }   return   $count  ;   }   echo   maxConsecutiveOnes  (  14  )   '  n  '  ;   ?>   

Ieșire
3  

Complexitatea timpului: O(1)
Spațiu auxiliar: O(1)

[O altă abordare] Utilizarea conversiei șirurilor

Inițializam două variabile max_len și cur_len la 0. Apoi repetăm ​​fiecare bit al întregului n. Dacă bitul cel mai puțin semnificativ (LSB) este 1, incrementăm cur_len pentru a număra rularea curentă de 1 secunde consecutive. Dacă LSB este 0, se rupe secvența curentă, așa că actualizăm max_len dacă cur_len este mai mare și resetăm cur_len la 0. După verificarea fiecărui bit, deplasăm la dreapta n cu 1 pentru a trece la următorul bit. În cele din urmă, după ce bucla se termină, efectuăm o ultimă actualizare a max_len dacă cur_len final este mai mare și returnăm max_len ca lungime a celei mai lungi secvențe de 1s consecutivi.

C++
   #include          #include          #include         using     namespace     std  ;   int     maxConsecutiveOnes  (  int     n  ){      string     binary     =     bitset   <  32  >  (  n  ).  to_string  ();      int     count     =     0  ;      int     maxCount     =     0  ;      // Loop through the binary string to      // find the longest consecutive 1s      for     (  int     i     =     0  ;     i      <     binary  .  size  ();     i  ++  )     {      if     (  binary  [  i  ]     ==     '1'  )     {      count  ++  ;      if     (  count     >     maxCount  )     {      maxCount     =     count  ;      }      }     else     {      count     =     0  ;      }      }      // Print the result      return     maxCount     ;       }   int     main  ()     {      int     n     =     14  ;      cout      < <     maxConsecutiveOnes  (  n  )      < <  'n'  ;      return     0  ;   }   
Java
   import     java.util.*  ;   public     class   Main     {      static     int     maxConsecutiveOnes  (  int     n  )     {      String     binary     =     String  .  format  (  '%32s'       Integer  .  toBinaryString  (  n  )).  replace  (  ' '       '0'  );      int     count     =     0  ;      int     maxCount     =     0  ;      // Loop through the binary string to      // find the longest consecutive 1s      for     (  int     i     =     0  ;     i      <     binary  .  length  ();     i  ++  )     {      if     (  binary  .  charAt  (  i  )     ==     '1'  )     {      count  ++  ;      if     (  count     >     maxCount  )     {      maxCount     =     count  ;      }      }     else     {      count     =     0  ;      }      }      // Return the result      return     maxCount  ;      }      public     static     void     main  (  String  []     args  )     {      int     n     =     14  ;      System  .  out  .  println  (  maxConsecutiveOnes  (  n  ));      }   }   
Python
   def   maxConsecutiveOnes  (  n  ):   binary   =   format  (  n     '032b'  )   count   =   0   maxCount   =   0   # Loop through the binary string to   # find the longest consecutive 1s   for   bit   in   binary  :   if   bit   ==   '1'  :   count   +=   1   if   count   >   maxCount  :   maxCount   =   count   else  :   count   =   0   # Return the result   return   maxCount   if   __name__   ==   '__main__'  :   n   =   14   print  (  maxConsecutiveOnes  (  n  ))   
C#
   using     System  ;   class     GFG   {      static     int     MaxConsecutiveOnes  (  int     n  )      {      string     binary     =     Convert  .  ToString  (  n       2  ).  PadLeft  (  32       '0'  );      int     count     =     0  ;      int     maxCount     =     0  ;      // Loop through the binary string to      // find the longest consecutive 1s      foreach     (  char     bit     in     binary  )      {      if     (  bit     ==     '1'  )      {      count  ++  ;      if     (  count     >     maxCount  )      maxCount     =     count  ;      }      else      {      count     =     0  ;      }      }      // Return the result      return     maxCount  ;      }      static     void     Main  ()      {      int     n     =     14  ;      Console  .  WriteLine  (  MaxConsecutiveOnes  (  n  ));      }   }   
JavaScript
   function     maxConsecutiveOnes  (  n  )     {      let     binary     =     n  .  toString  (  2  ).  padStart  (  32       '0'  );      let     count     =     0  ;      let     maxCount     =     0  ;      // Loop through the binary string to      // find the longest consecutive 1s      for     (  let     i     =     0  ;     i      <     binary  .  length  ;     i  ++  )     {      if     (  binary  [  i  ]     ===     '1'  )     {      count  ++  ;      if     (  count     >     maxCount  )     {      maxCount     =     count  ;      }      }     else     {      count     =     0  ;      }      }      // Return the result      return     maxCount  ;   }   // Driver code   let     n     =     14  ;   console  .  log  (  maxConsecutiveOnes  (  n  ));   

Ieșire
3  


 

Creați un test