Dado un entero positivo N , la tarea es encontrar un número que contenga (N – 1) bits establecidos en su forma binaria en cada índice par (basado en 1) desde la derecha.
Ejemplos:
Entrada: N = 2
Salida: 2 La
representación binaria de 2 es 10, que tiene
1 bit establecido en la posición par desde la derecha.
Entrada: N = 4
Salida: 42 La
representación binaria de 42 es 101010
Observación: si revisamos los números en forma binaria, el resultado es algo como esto:
norte | Equivalente decimal | Equivalente binario |
---|---|---|
1 | 0 | 0 |
2 | 2 | 10 |
3 | 10 | 1010 |
4 | 42 | 101010 |
5 | 170 | 10101010 |
Enfoque ingenuo: como podemos ver en la tabla, nuestro equivalente binario siempre agrega un «10» al final de la string anterior. Entonces, podemos generar una string binaria que se compone de la substring «10» concatenada N-1 veces y luego imprimir su equivalente decimal.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; #define ll long long int // Function to return the string generated // by appending "10" n-1 times string constructString(ll n) { // Initialising string as empty string s = ""; for (ll i = 0; i < n; i++) { s += "10"; } return s; } // Function to return the decimal equivalent // of the given binary string ll binaryToDecimal(string n) { string num = n; ll dec_value = 0; // Initializing base value to 1 // i.e 2^0 ll base = 1; ll len = num.length(); for (ll i = len - 1; i >= 0; i--) { if (num[i] == '1') dec_value += base; base = base * 2; } return dec_value; } // Function that calls the constructString // and binarytodecimal and returns the answer ll findNumber(ll n) { string s = constructString(n - 1); ll num = binaryToDecimal(s); return num; } // Driver code int main() { ll n = 4; cout << findNumber(n); return 0; }
Java
// Java implementation of above approach import java.util.*; class GFG { // Function to return the String generated // by appending "10" n-1 times static String constructString(int n) { // Initialising String as empty String s = ""; for (int i = 0; i < n; i++) { s += "10"; } return s; } // Function to return the decimal equivalent // of the given binary String static int binaryToDecimal(String n) { String num = n; int dec_value = 0; // Initializing base value to 1 // i.e 2^0 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { if (num.charAt(i) == '1') dec_value += base; base = base * 2; } return dec_value; } // Function that calls the constructString // and binarytodecimal and returns the answer static int findNumber(int n) { String s = constructString(n - 1); int num = binaryToDecimal(s); return num; } // Driver code public static void main(String[] args) { int n = 4; System.out.println(findNumber(n)); } } /* This code is contributed by PrinciRaj1992 */
Python
# Python3 implementation of the approach # Function to return the generated # by appending "10" n-1 times def constructString(n): # Initialising as empty s = "" for i in range(n): s += "10" return s # Function to return the decimal equivaLent # of the given binary string def binaryToDecimal(n): num = n dec_value = 0 # Initializing base value to 1 # i.e 2^0 base = 1 Len = len(num) for i in range(Len - 1,-1,-1): if (num[i] == '1'): dec_value += base base = base * 2 return dec_value # Function that calls the constructString # and binarytodecimal and returns the answer def findNumber(n): s = constructString(n - 1) num = binaryToDecimal(s) return num # Driver code n = 4 print(findNumber(n)) # This code is contributed by mohit kumar 29
C#
// C# implementation of above approach using System; class GFG { // Function to return the String generated // by appending "10" n-1 times static String constructString(int n) { // Initialising String as empty String s = ""; for (int i = 0; i < n; i++) { s += "10"; } return s; } // Function to return the decimal equivalent // of the given binary String static int binaryToDecimal(String n) { String num = n; int dec_value = 0; // Initializing base value to 1 // i.e 2^0 int base_t = 1; int len = num.Length; for (int i = len - 1; i >= 0; i--) { if (num[i] == '1') dec_value = dec_value + base_t; base_t = base_t * 2; } return dec_value; } // Function that calls the constructString // and binarytodecimal and returns the answer static int findNumber(int n) { String s = constructString(n - 1); int num = binaryToDecimal(s); return num; } // Driver code static public void Main () { int n = 4; Console.Write(findNumber(n)); } } // This code is contributed by ajit
Javascript
<script> // JavaScript implementation of above approach // Function to return the String generated // by appending "10" n-1 times function constructString(n) { // Initialising String as empty var s = ""; for (var i = 0; i < n; i++) { s += "10"; } return s; } // Function to return the decimal equivalent // of the given binary String function binaryToDecimal(n) { var num = n; var dec_value = 0; // Initializing base value to 1 // i.e 2^0 var base = 1; var len = num.length; for (var i = len - 1; i >= 0; i--) { if (num.charAt(i) == '1') dec_value += base; base = base * 2; } return dec_value; } // Function that calls the constructString // and binarytodecimal and returns the answer function findNumber(n) { var s = constructString(n - 1); var num = binaryToDecimal(s); return num; } // Driver code var n = 4; document.write(findNumber(n)); // This code is contributed by Amit Katiyar </script>
42
Enfoque eficiente: si tomamos los números y los convertimos a base 4, podemos ver un patrón interesante de la siguiente manera:
norte | Equivalente decimal | Equivalente binario | Base_4 |
---|---|---|---|
1 | 0 | 0 | 0 |
2 | 2 | 10 | 2 |
3 | 10 | 1010 | 22 |
4 | 42 | 101010 | 222 |
5 | 170 | 10101010 | 2222 |
De hecho, estamos agregando «2» para cada término n en base 4, es decir, para n = 7 , nuestro número en base 4 tendría (n – 1), es decir , 6 2 consecutivos .
Ahora debemos tener en cuenta un punto, ya que sabemos que si convertimos cualquier base m a base 10 , es decir, decimal, la solución es (n0 * m 0 + n1 * m 1 + n2 * m 2 + …. + n * m n ) . Entonces, como nuestra base es 4 mediante un cálculo adicional, podemos encontrar que nuestro número requerido n se puede encontrar usando la fórmula deducida en O (1)complejidad del tiempo.
Fórmula:
A(n) = piso((2 / 3) * (4 n – 1 ))
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; #define ll long long int // Function to compute number // using our deduced formula ll findNumber(int n) { // Initialize num to n-1 ll num = n - 1; num = 2 * (ll)pow(4, num); num = floor(num / 3.0); return num; } // Driver code int main() { int n = 5; cout << findNumber(n); return 0; }
Java
// Java implementation of the approach import java.io.*; class GFG { // Function to compute number // using our deduced formula static int findNumber(int n) { // Initialize num to n-1 int num = n - 1; num = 2 * (int)Math.pow(4, num); num = (int)Math.floor(num / 3.0); return num; } // Driver code public static void main (String[] args) { int n = 5; System.out.println (findNumber(n)); } } // The code is contributed by ajit.
Python3
# Python3 implementation of the approach # Function to compute number # using our deduced formula def findNumber(n) : # Initialize num to n-1 num = n - 1; num = 2 * (4 ** num); num = num // 3; return num; # Driver code if __name__ == "__main__" : n = 5; print(findNumber(n)); # This code is contributed by AnkitRai01
C#
// C# implementation of the approach using System; class GFG { // Function to compute number // using our deduced formula static int findNumber(int n) { // Initialize num to n-1 int num = n - 1; num = 2 * (int)Math.Pow(4, num); num = (int)Math.Floor(num / 3.0); return num; } // Driver code static public void Main () { int n = 5; Console.Write(findNumber(n)); } } // The code is contributed by Tushil.
Javascript
<script> // Javascript implementation of the approach // Function to compute number // using our deduced formula function findNumber(n) { // Initialize num to n-1 let num = n - 1; num = 2 * Math.pow(4, num); num = Math.floor(num / 3.0); return num; } let n = 5; document.write(findNumber(n)); </script>
170
Complejidad de tiempo: O(1)
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por ShivamChauhan5 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA