aboutsummaryrefslogtreecommitdiff
path: root/guess_number_high_low.cpp
blob: d31ca99b2e751c0bc461f356652139795bad3d5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "leetcode.h"

class Solution {
public:
  int guessNumber(int n) {
    int left = 1, right = n, mid = n / 2;
    while (left <= right) {
      int ans = guess(mid); // guess is api call
      if (!ans)
        return mid;
      left = ans < 0 ? left : mid + 1;
      right = ans < 0 ? mid - 1 : right;
      mid = left + (right - left) / 2;
    }
    return -1;
  }
};

int main() {
  Solution obj;
  cout << obj.guessNumber(10);
}