Absolute difference between the first X and last X Digits of N | Java implementation of the above approach ; Function to find the number of digits in the integer ; Function to find the absolute difference ; Store the last x digits in last ; Count the no . of digits in N ; Remove the digits except the first x ; Store the first x digits in first ; Return the absolute difference between the first and last ; Driver code
import java . util . * ; class GFG { static int digitsCount ( int n ) { int len = 0 ; while ( n > 0 ) { len ++ ; n /= 10 ; } return len ; } static int absoluteFirstLast ( int n , int x ) { int i = 0 , mod = 1 ; while ( i < x ) { mod *= 10 ; i ++ ; } int last = n % mod ; int len = digitsCount ( n ) ; while ( len != x ) { n /= 10 ; len -- ; } int first = n ; return Math . abs ( first - last ) ; } public static void main ( String args [ ] ) { int n = 21546 , x = 2 ; System . out . println ( absoluteFirstLast ( n , x ) ) ; } }