Dado un entero n , la tarea es contar los números que tienen solo 1 bit establecido en el rango [0, n] .
Ejemplos:
Entrada: n = 7
Salida: 3
Explicación: 000, 001, 010, 011, 100, 101, 110 y 111 son la representación binaria de todos los números hasta el 7. Y solo hay 3 números (001, 010 y 100) que tienen solo 1 juego de bits.Entrada: n = 3
Salida: 2
Enfoque: si se requieren k bits para representar n , entonces hay k números posibles ya que 1 puede colocarse en k posiciones diferentes cada vez.
A continuación se muestra la implementación del enfoque anterior.
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the required count int count(int n) { // To store the count of numbers int cnt = 0; int p = 1; while (p <= n) { cnt++; // Every power of 2 contains // only 1 set bit p *= 2; } return cnt; } // Driver code int main() { int n = 7; cout << count(n); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the required count static int count(int n) { // To store the count of numbers int cnt = 0; int p = 1; while (p <= n) { cnt++; // Every power of 2 contains // only 1 set bit p *= 2; } return cnt; } // Driver code public static void main(String args[]) { int n = 7; System.out.print(count(n)); } }
C#
// C# implementation of the approach using System; class GFG { // Function to return the required count static int count(int n) { // To store the count of numbers int cnt = 0; int p = 1; while (p <= n) { cnt++; // Every power of 2 contains // only 1 set bit p *= 2; } return cnt; } // Driver code public static void Main() { int n = 7; Console.Write(count(n)); } }
Python3
# Python3 implementation of the approach # Function to return the required count def count(n): # To store the count of numbers cnt = 0 p = 1 while (p <= n): cnt = cnt + 1 # Every power of 2 contains # only 1 set bit p *= 2 return cnt # Driver code n = 7 print(count(n));
PHP
<?php // PHP implementation of the approach // Function to return the required count function count_t($n) { // To store the count of numbers $cnt = 0; $p = 1; while ($p <= $n) { $cnt++; // Every power of 2 contains // only 1 set bit $p *= 2; } return $cnt; } // Driver code $n = 7; echo count_t($n); // This Code is contributed by ajit. ?>
Javascript
<script> // Javascript implementation of the approach // Function to return the required count function count(n) { // To store the count of numbers var cnt = 0; var p = 1; while (p <= n) { cnt++; // Every power of 2 contains // only 1 set bit p *= 2; } return cnt; } // Driver code var n = 7; document.write(count(n)); // This code is contributed by noob2000. </script>
Producción
3
Complejidad temporal: O(log n)
Espacio auxiliar: O(1)