Dado un número entero N , la tarea es encontrar un número entero K tal que la suma de los números formados por la eliminación repetida del último dígito de K sea igual a N.
Ejemplos:
Entrada: N = 136
Salida: 123
Explicación:
Los números formados al quitar repetidamente el último dígito de 123 son {123, 12, 1}.
Por tanto, la suma de estos números = 123 + 12 + 1 = 136( = N).Entrada: N = 107
Salida: 98
Explicación:
Los números formados al eliminar repetidamente el último dígito de 98 son {98, 9}.
Por lo tanto, la suma de estos números = 98 + 7 = 107( = N).
Enfoque: El enfoque se basa en las siguientes observaciones:
- Considere K = 123 .
- Los posibles números formados a partir de 123 son 1, 12 y 123.
- Ahora, 123 se puede expresar como 100 + 20 + 3. Si todos los demás números se expresan de manera similar, entonces la idea es conocer la posición y la frecuencia de cada dígito en todos los números combinados, para obtener la suma total como N .
Dígito Frecuencia de cada dígito Suma unidades decenas cientos 1 1 1 1 1*1 + 1*10 + 1*100 = 111 2 1 1 2*1 + 2*10 = 22 3 1 3*1 = 3
- Ahora, para el número dado N de longitud L . Divide el número con L número de 1 s para obtener el dígito del lugar más alto.
- Calcular el resto que será nuestro recién formado N .
- Nuevamente divida la N recién formada con (L – 1) número de 1 s para obtener el segundo dígito del lugar más alto y continúe hasta que la L se convierta en 0 .
Siga los pasos a continuación para resolver el problema:
- Sea L el conteo de dígitos en el número dado N .
- Inicialice la string str como L números de 1 s en ella.
- Inicialice una variable ans como cero que almacenará el número resultante K .
- Itere hasta que la string str no esté vacía y siga los pasos a continuación:
- Convierta la string str en número usando la función stoi() y guárdela en M .
- Divida N por M y actualice ans como:
respuesta = respuesta*10 + (N/M)
- Actualizar N a N % M .
- Elimina el último carácter de la string str.
- Después de los pasos anteriores, imprima el valor almacenado en ans , que es el valor requerido de K .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the value of K int findK(int N, int l) { // Stores l number of 1s string ones = ""; while (l--) { // Storing 1's ones = ones + '1'; } // Stores the value of K int ans = 0; // Iterate until ones is empty while (ones != "") { // Convert ones to number int m = stoi(ones); // Update the ans ans = (ans * 10) + (N / m); // Update N to N%m N = N % m; // Removing last digit from ones ones.pop_back(); } // Return the value of K return ans; } // Driver Code int main() { // Given number N int N = 136; // Number of digits in N int L = to_string(N).length(); // Function Call cout << findK(N, L); return 0; }
Java
// Java program for // the above approach import java.util.*; class GFG{ // Function to find the // value of K static int findK(int N, int l) { // Stores l number of 1s String ones = ""; while (l-- > 0) { // Storing 1's ones += '1'; } // Stores the value of K int ans = 0; // Iterate until ones is empty while (!ones.equals("")) { // Convert ones to number int m = Integer.valueOf(ones); // Update the ans ans = (ans * 10) + (N / m); // Update N to N%m N = N % m; // Removing last digit from ones ones = ones.substring(0, ones.length() - 1); } // Return the value of K return ans; } // Driver Code public static void main(String[] args) { // Given number N int N = 136; // Number of digits in N int L = String.valueOf(N).length(); // Function Call System.out.print(findK(N, L)); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program for # the above approach # Function to find # the value of K def findK(N, l): # Stores l number of 1s ones = "" while (l): # Storing 1's ones = ones + '1' l -= 1 # Stores the value of K ans = 0 # Iterate until ones # is empty while (ones != ""): # Convert ones to number m = int(ones) # Update the ans ans = (ans * 10) + (N // m) # Update N to N%m N = N % m # Removing last digit from ones ones = ones.replace(ones[-1], "", 1) # Return the value of K return ans # Driver Code if __name__ == "__main__": # Given number N N = 136 # Number of digits in N L = len(str(N)) # Function Call print (findK(N, L)) # This code is contributed by Chitranayal
C#
// C# program for // the above approach using System; class GFG{ // Function to find the // value of K static int findK(int N, int l) { // Stores l number of 1s String ones = ""; while (l-- > 0) { // Storing 1's ones += '1'; } // Stores the value of K int ans = 0; // Iterate until ones is empty while (!ones.Equals("")) { // Convert ones to number int m = Int32.Parse(ones); // Update the ans ans = (ans * 10) + (N / m); // Update N to N%m N = N % m; // Removing last digit from ones ones = ones.Substring(0, ones.Length - 1); } // Return the value of K return ans; } // Driver Code public static void Main(String[] args) { // Given number N int N = 136; // Number of digits in N int L = String.Join("", N).Length; // Function Call Console.Write(findK(N, L)); } } // This code is contributed by Princi Singh
Javascript
<script> // JavaScript program for // the above approach // Function to find the // value of K function findK(N, l) { // Stores l number of 1s var ones = ""; while (l) { // Storing 1's ones += "1"; l -= 1; } // Stores the value of K var ans = 0; // Iterate until ones is empty while (ones !== "") { // Convert ones to number var m = parseInt(ones); // Update the ans ans = parseInt(ans * 10 + N / m); // Update N to N%m N = N % m; // Removing last digit from ones ones = ones.substring(0, ones.length - 1); } // Return the value of K return ans; } // Driver Code // Given number N var N = 136; // Number of digits in N var L = N.toString().length; // Function Call document.write(findK(N, L)); </script>
123
Complejidad de tiempo: O(log 10 N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por vandanakillari54935 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA