K | c ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void kthDigitFromLast ( int n , int k ) { if ( k <= 0 ) { cout << -1 << endl ; return ; } string temp = to_string ( n ) ; if ( k > temp . length ( ) ) { cout << -1 << endl ; } else { cout << temp [ temp . length ( ) - k ] - '0' ; } } int main ( ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; }