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 ; Divide the number n by 10 upto k - 1 times ; If the number n is equal 0 ; Print the right most digit ; 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 ; } while ( ( k - 1 ) > 0 && n > 0 ) { n = n / 10 ; k -- ; } if ( n == 0 ) { cout << -1 << endl ; } else { cout << n % 10 << endl ; } } int main ( ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; }