Absolute difference between the first X and last X Digits of N | 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 program
function digitsCount ( n ) { let len = 0 ; while ( n > 0 ) { len ++ ; n = Math . floor ( n / 10 ) ; } return len ; } function absoluteFirstLast ( n , x ) { let i = 0 , mod = 1 ; while ( i < x ) { mod *= 10 ; i ++ ; } let last = n % mod ; let len = digitsCount ( n ) ; while ( len != x ) { n = Math . floor ( n / 10 ) ; len -- ; } let first = n ; return Math . abs ( first - last ) ; } let n = 21546 , x = 2 ; document . write ( absoluteFirstLast ( n , x ) ) ;