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 code
< ? php function digitsCount ( $ n ) { $ len = 0 ; while ( $ n > 0 ) { $ len ++ ; $ n = ( int ) ( $ n / 10 ) ; } return $ len ; } function absoluteFirstLast ( $ n , $ x ) { $ i = 0 ; $ mod = 1 ; while ( $ i < $ x ) { $ mod *= 10 ; $ i ++ ; } $ last = $ n % $ mod ; $ len = digitsCount ( $ n ) ; while ( $ len != $ x ) { $ n = ( int ) ( $ n / 10 ) ; $ len -- ; } $ first = $ n ; return abs ( $ first - $ last ) ; } $ n = 21546 ; $ x = 2 ; echo absoluteFirstLast ( $ n , $ x ) ; ? >