本文主要是介绍LeetCode - 374,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:https://leetcode.com/problems/guess-number-higher-or-lower/description/
猜数字大小,返回1表示小了,-1表示大了,0表示正确
跟昨天写的704差不多
int guess(int num);class Solution {
public:int guessNumber(int n) {int l = 1;int r = n;int ans = -1;int mid;while(l < r){mid = l / 2 + r / 2;if(guess(mid) == 0){ans = mid;break;}else if(guess(mid) == 1){l = mid+1;}else if(guess(mid) == -1){r = mid;}}if(ans == -1){if(guess(1) == 0){ans = 1;}else if(guess(n) == 0){ans = n;}}return ans;}
};
这篇关于LeetCode - 374的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!