Given an integer N, the task is to find the Kth digit from the end of an integer N. If the Kth digit is not present, then print -1.
Examples:
Input: N = 2354, K = 2
Output: 5Input: N = 1234, K = 1
Output: 4
Naive Approach: This simplest approach to solve this problem is converting the integer N to string. Follow the steps below to solve this problem:
- If K is less than equal to 0, then print -1 and return.
- Convert N into string and store in temp.
- If K is greater than size of temp, then print -1, otherwise print K character from last.
Below is the implementation of the above approach:
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
Time complexity: O(d), where d is the number of digits in number N.
Auxiliary Space: O(d)
Efficient Approach: This problem can be solved by iterating over the digits of the number N. Follow the steps below to solve this problem:Â
- If K is less than equal to 0, then print -1 and return.
- Iterate while N and K-1 are greater than 0 :
- Update N as N/10 and decrement K by 1.
- If N is 0, then print -1, otherwise print N%10.
Below is the implementation of the above approach:Â
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
Time complexity: O(d), where d is the number of digits in number N.
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved using power function. Follow the steps below to solve this problem:
- If K is less than equal to 0, then print -1 and return.
- Initialize a variable say, divisor as pow(10, K-1).
- If divisor is greater than N, then print -1, otherwise print (N/divisor) %10.
Below is the implementation of the above approach:Â
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
Time complexity: O(log(K)), where d is the number of digits in number N. This time complexity is due to the calculation of power of 10 using power function.
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!