
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Guess Number Higher or Lower in C++
Suppose we are playing the Guess Game. The properties of this game is as follows −
Player 1 will pick a number from 1 to n. player2 have to guess which number I picked. Every time player2 guess wrong, player1 will tell player2 whether the number is higher or lower.
We can use the function guess(num) which will return 3 possible results as follows −
-1 − Player1's number is lower
1 − Player1's number is higher
0 − Number is matched
So, if the input is like n = 10, pick = 5, then the output will be 5.
To solve this, we will follow these steps −
l := 1,r := n
-
while l −= r, do −
m := l+(r - l)/2
-
if guess(m) is the same as 0, then −
return m
-
if guess(m) is the same as -1, then −
r := m - 1
-
Otherwise
l := m + 1
return 0
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { private: int number; int guess(int num){ if(number > num) return 1; if(number < num) return -1; return 0; } public: Solution(int n){ number = n; } int guessNumber(int n) { int l=1,r=n,m; while(l<=r){ m=l+(r-l)/2; if(guess(m)==0) return m; if(guess(m)==-1) r=m-1; else l=m+1; } return 0; } }; main(){ Solution ob(5); //pick = 5 cout << (ob.guessNumber(10)); }
Input
5,10
Output
5