We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
- -1: Your guess is higher than the number I picked (i.e.- num > pick).
- 1: Your guess is lower than the number I picked (i.e.- num < pick).
- 0: your guess is equal to the number I picked (i.e.- num == pick).
Return the number that I picked.
Example 1:
Input: n = 10, pick = 6 Output: 6
Example 2:
Input: n = 1, pick = 1 Output: 1
Example 3:
Input: n = 2, pick = 1 Output: 1
Solution
/** 
 * Forward declaration of guess API.
 * @param {number} num   your guess
 * @return 	     -1 if num is higher than the picked number
 *			      1 if num is lower than the picked number
 *               otherwise return 0
 * var guess = function(num) {}
 */
/**
 * @param {number} n
 * @return {number}
 */
 function middle(start,end){
     let mid = 1;
     if((start % 2)==0 && (end % 2 == 0)){
        return (start+end)/2;
     }
     else if((start % 2)!=0 && (end % 2 != 0)){
         return (start+end)/2;
     }
     else if((start % 2)==0 && (end % 2 != 0)){
         return (start+(end-1))/2;
     }
     else if((start % 2)!=0 && (end % 2 == 0)){
         return ((start - 1)+end)/2;
     }
     return mid;
 }
 function findnum(start,end){
     const mid = middle(start,end);
        
        if (guess(mid) === 0) return mid;
        if (guess(mid) === -1) return findnum(start, mid - 1);
        if (guess(mid) === 1) return findnum(mid + 1, end);
 }
var guessNumber = function(n) {
   if(guess(n) == 0){
       return n;
   }
return findnum(1,n);
};A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.
