K | Java program for the above approach ; Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the string temp ; Print the k digit from last ; Driver code ; Given Input ; Function call
import java . io . * ; class GFG { public static void kthDigitFromLast ( int n , int k ) { if ( k <= 0 ) { System . out . println ( - 1 ) ; return ; } String temp = Integer . toString ( n ) ; if ( k > temp . length ( ) ) { System . out . println ( - 1 ) ; } else { int index = temp . length ( ) - k ; int res = temp . charAt ( index ) - '0' ; System . out . println ( res ) ; } } public static void main ( String [ ] args ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; } }