leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

guess-number-higher-or-lower.cpp (1087B)


      1 #include <iostream>
      2 
      3 using namespace std;
      4 
      5 
      6 //Leet Ratings
      7 //       Speed  Memory
      8 //Total  0ms    6.1MB    
      9 //Beats  100%   8.48%
     10 
     11 
     12 //This is the function to return if guess is higher or lower than the actual value.
     13 int guess(int n){
     14     if(n > 5){
     15         return -1;
     16     }
     17     if(n < 5){
     18         return 1;
     19     }
     20     if(n == 5){
     21         return 0;
     22     }
     23     return 100;
     24 
     25 }
     26 
     27 //This is the logic from the leet-code problem that loops through the list using a binary search until the answer is guessed.
     28 int guessNumber(int n) {
     29    unsigned long int lower_bound = 0;
     30    unsigned long int upper_bound = n;
     31     while(true){
     32         unsigned long int guess_int = (lower_bound + upper_bound) / 2;
     33         unsigned long int guess_val = guess(guess_int + 1);
     34         if(guess_val == -1){
     35             upper_bound = guess_int;
     36         }
     37         if(guess_val == 1){
     38             lower_bound = guess_int;
     39         }
     40         if(guess_val == 0){
     41             return guess_int + 1;
     42         }
     43     }
     44     return 0;
     45 }
     46 
     47 //Constructor method.
     48 int main(){
     49     int number = guessNumber(5);
     50     cout << number;
     51 
     52 
     53 }
     54 
     55