Dado un número entero N , la tarea es encontrar el K -ésimo dígito desde el final de un número entero N. Si el K -ésimo dígito no está presente, imprima -1 .
Ejemplos:
Entrada : N = 2354, K = 2
Salida : 5Entrada : N = 1234, K = 1
Salida : 4
Enfoque ingenuo: el enfoque más simple para resolver este problema es convertir el número entero N en una string. Siga los pasos a continuación para resolver este problema:
- Si K es menor que igual a 0, imprima -1 y regrese.
- Convierta N en string y guárdelo en temp .
- Si K es mayor que el tamaño de temp , imprima -1 , de lo contrario, imprima el carácter K desde el último.
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 kth digit // from last in an integer n void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { cout << -1 << endl; return; } // Convert integer into string string temp = to_string(n); // If k is greater than length of the // string temp if (k > temp.length()) { cout << -1 << endl; } // Print the k digit from last else { cout << temp[temp.length() - k] - '0'; } } // Driver code int main() { // Given Input int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); }
Java
// Java program for the above approach import java.io.*; class GFG{ // Function to find the kth digit // from last in an integer n public static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { System.out.println(-1); return; } // Convert integer into string String temp = Integer.toString(n); // If k is greater than length of the // string temp if (k > temp.length()) { System.out.println(-1); } // Print the k digit from last else { int index = temp.length() - k; int res = temp.charAt(index) - '0'; System.out.println(res); } } // Driver code public static void main(String[] args) { // Given Input int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by Potta Lokesh
Python3
# Python3 program for the above approach # Function to find the kth digit # from last in an integer n def kthDigitFromLast(n, k): # If k is less than equal to 0 if (k <= 0): print(-1) return # Convert integer into string temp = str(n) # If k is greater than length of the # temp if (k > len(temp)): print(-1) # Print the k digit from last else: print(ord(temp[len(temp) - k]) - ord('0')) # Driver code if __name__ == '__main__': # Given Input n = 2354 k = 2 # Function call kthDigitFromLast(n, k) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to find the kth digit // from last in an integer n static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { Console.Write(-1); return; } // Convert integer into string string temp = n.ToString(); // If k is greater than length of the // string temp if (k > temp.Length) { Console.WriteLine(-1); } // Print the k digit from last else { Console.Write(temp[temp.Length - k] - 48); } } // Driver code public static void Main() { // Given Input int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by SURENDRA_GANGWAR
Javascript
<script> // JavaScript program for the above approach // Function to find the kth digit // from last in an integer n function kthDigitFromLast(n, k) { // If k is less than equal to 0 if (k <= 0) { document.write(-1); return; } // Convert integer into string var temp = String(n); // If k is greater than length of the // string temp if (k > temp.length) { document.write(-1); } // Print the k digit from last else { var req = temp.charAt(temp.length - k) // Convert to number again document.write(Number(req)); } } // Driver code // Given Input var n = 2354; var k = 2; // Function call kthDigitFromLast(n, k); // This code is contributed by Potta Lokesh </script>
5
Complejidad temporal: O(d), donde d es el número de dígitos en el número N .
Espacio Auxiliar: O(d)
Enfoque eficiente : este problema se puede resolver iterando sobre los dígitos del número N. Siga los pasos a continuación para resolver este problema:
- Si K es menor que igual a 0, imprima -1 y regrese.
- Iterar mientras N y K-1 son mayores que 0 :
- Actualice N como N/10 y disminuya K en 1 .
- Si N es 0 , imprima -1 ; de lo contrario, imprima N%10 .
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 kth digit // from last in an integer n void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { cout << -1 << endl; return; } // Divide the number n by 10 // upto k-1 times while ((k - 1) > 0 && n > 0) { n = n / 10; k--; } // If the number n is equal 0 if (n == 0) { cout << -1 << endl; } // Print the right most digit else { cout << n % 10 << endl; } } // Driver code int main() { // Given Input int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); }
Java
// Java program for the above approach import java.io.*; class GFG{ // Function to find the kth digit // from last in an integer n public static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { System.out.println(-1); return; } // Divide the number n by 10 // upto k-1 times while ((k - 1) > 0 && n > 0) { n = n / 10; k--; } // If the number n is equal 0 if (n == 0) { System.out.println(-1); } // Print the right most digit else { System.out.println(n % 10); } } // Driver code public static void main(String[] args) { int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by Potta Lokesh
Python3
# Python program for the above approach # Function to find the kth digit # from last in an eger n def kthDigitFromLast( n, k): # If k is less than equal to 0 if (k <= 0): print("-1") return # Divide the number n by 10 # upto k-1 times while ((k - 1) > 0 and n > 0): n = n / 10 k -= 1 # If the number n is equal 0 if (n == 0): print("-1") # Pr the right most digit else: print(int(n % 10 )) # Driver code if __name__ == '__main__': # Given Input n = 2354 k = 2 # Function call kthDigitFromLast(n, k) # this code is contributed by shivanisinghss2110
C#
// C# program for the above approach using System; class GFG { // Function to find the kth digit // from last in an integer n public static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { Console.Write(-1); return; } // Divide the number n by 10 // upto k-1 times while ((k - 1) > 0 && n > 0) { n = n / 10; k--; } // If the number n is equal 0 if (n == 0) { Console.Write(-1); } // Print the right most digit else { Console.Write(n % 10); } } // Driver code public static void Main(String[] args) { int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by shivanisinghss2110
Javascript
<script> // JavaScript program for the above approach // Function to find the kth digit // from last in an integer n function kthDigitFromLast(n, k) { // If k is less than equal to 0 if (k <= 0) { document.write(-1); return; } // Divide the number n by 10 // upto k-1 times while ((k - 1) > 0 && n > 0) { n = n / 10; k--; } // If the number n is equal 0 if (n == 0) { document.write(-1); } // Print the right most digit else { document.write(parseInt(n % 10)); } } // Driver code // Given Input var n = 2354; var k = 2; // Function call kthDigitFromLast(n, k); // This code is contributed by Potta Lokesh </script>
5
Complejidad temporal: O(d), donde d es el número de dígitos en el número N .
Espacio Auxiliar: O(1)
Enfoque eficiente: este problema se puede resolver utilizando la función de potencia . Siga los pasos a continuación para resolver este problema:
- Si K es menor que igual a 0, imprima -1 y regrese.
- Inicialice una variable, digamos, divisor como pow (10, K-1).
- Si el divisor es mayor que N, imprima -1; de lo contrario, imprima (N/divisor) %10.
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 kth digit // from last in an integer n void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { cout << -1 << endl; return; } // Calculate kth digit using power function int divisor = (int)pow(10, k - 1); // If divisor is greater than n if (divisor > n) { cout << -1 << endl; } // Otherwise print kth digit from last else { cout << (n / divisor) % 10 << endl; } } // Driver code int main() { // Given Input int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); }
Java
// Java program for the above approach import java.io.*; class GFG{ // Function to find the kth digit // from last in an integer n public static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { System.out.println(-1); return; } // Calculate kth digit using power function int diviser = (int)Math.pow(10, k - 1); // If diviser is greater than n if (diviser > n) { System.out.println(-1); } // Otherwise print kth digit from last else { System.out.println((n / diviser) % 10); } } // Driver code public static void main(String[] args) { int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by Potta Lokesh
Python3
# Python program for the above approach # Function to find the kth digit # from last in an integer n def kthDigitFromLast(n, k): # If k is less than equal to 0 if (k <= 0): print("-1") return # Calculate kth digit using power function divisor = int(pow(10, k - 1)) # If divisor is greater than n if (divisor > n): print("-1") # Otherwise print kth digit from last else: print(int((n / divisor) % 10)) # Given Input n = 2354; k = 2; # Function call kthDigitFromLast(n, k); # This code is contributed by SoumikMondal
C#
// C# program for the above approach using System; class GFG{ // Function to find the kth digit // from last in an integer n public static void kthDigitFromLast(int n, int k) { // If k is less than equal to 0 if (k <= 0) { Console.Write(-1); return; } // Calculate kth digit using power function int diviser = (int)Math.Pow(10, k - 1); // If diviser is greater than n if (diviser > n) { Console.Write(-1); } // Otherwise print kth digit from last else { Console.Write((n / diviser) % 10); } } // Driver code public static void Main(String[] args) { int n = 2354; int k = 2; // Function call kthDigitFromLast(n, k); } } // This code is contributed by shivanisinghss2110
Javascript
<script> // JavaScript program for the above approach function kthDigitFromLast(n, k) { // If k is less than equal to 0 if (k <= 0) { document.write(-1); return; } // Calculate kth digit using power function var diviser = parseInt(Math.pow(10, k - 1)); // If diviser is greater than n if (diviser > n) { document.write(-1); } // Otherwise print kth digit from last else { document.write(parseInt((n / diviser) % 10)); } } // Driver code // Given Input var n = 2354; var k = 2; // Function call kthDigitFromLast(n, k); // This code is contributed by Potta Lokesh </script>
5
Complejidad del tiempo: O(log(K)), donde d es el número de dígitos en el número N . Esta complejidad de tiempo se debe al cálculo de la potencia de 10 utilizando la función de potencia.
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por scorchingeagle y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA