In an array first we have to find whether a desired number exists in that or not? If not then how will I find nearer number to the given desired number in Java?
Another common definition of "closer" is based on the square of the difference. The outline is similar to that provided by romaintaz, except that you'd compute
long d = ((long)desiredNumber - array[i]);
and then compare (d * d)
to the nearest distance.
Note that I've typed d
as long
rather than int
to avoid overflow, which can happen even with the absolute-value-based calculation. (For example, think about what happens when desiredValue
is at least half of the maximum 32-bit signed value, and the array contains a value with corresponding magnitude but negative sign.)
Finally, I'd write the method to return the index of the value located, rather than the value itself. In either of these two cases:
you can use -1
as an out-of-band value similar to the spec on indexOf
.