Finding closest number in an array

前端 未结 11 905
萌比男神i
萌比男神i 2021-01-31 22:10

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?

11条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 22:57

       int d = Math.abs(desiredNumber - array[i]);
        if (d < bestDistanceFoundYet) {
          // For the moment, this value is the nearest to the desired number...
          nearest = array[i];
        }
    

    In this way you find the last number closer to desired number because bestDistanceFoundYet is constant and d memorize the last value passign the if (d<...).

    If you want found the closer number WITH ANY DISTANCE by the desired number (d is'nt matter), you can memorize the last possibile value. At the if you can test

    if(d

提交回复
热议问题