text: Least number to be added to or subtracted from N to make it a Perfect Cube | Java implementation of the approach ; Function to return the Least number ; Get the perfect cube before and after N ; Check which is nearest to N ; return the result ; Driver code
code: class GFG { static int nearest ( int n ) { int prevCube = ( int ) Math . cbrt ( n ) ; int nextCube = prevCube + 1 ; prevCube = prevCube * prevCube * prevCube ; nextCube = nextCube * nextCube * nextCube ; int ans = ( n - prevCube ) < ( nextCube - n ) ? ( prevCube - n ) : ( nextCube - n ) ; return ans ; } public static void main ( String [ ] args ) { int n = 25 ; System . out . println ( nearest ( n ) ) ; n = 27 ; System . out . println ( nearest ( n ) ) ; n = 40 ; System . out . println ( nearest ( n ) ) ; } }