374. Guess Number Higher or Lower
2024-08-27 06:38:57
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.
我从1到n之间选择一个数字,由你来猜我选了哪个数字。
Every time you guess wrong, I'll tell you whether the number is higher or lower.
在你每次猜错后,我会告诉你我选的数字比你猜的数字高还是低。
You call a pre-defined API guess(int num)
which returns 3 possible results (-1
, 1
, or 0
):
你可以用一个已经准备好的接口guess(int num),它会返回3个可能的结果(-1,1或0):
-1 : My number is lower //我的数字更小
1 : My number is higher //我的数字更大
0 : Congrats! You got it! //猜中了
刚开始第一次提交采用了二分查找,不过显示超时了。
超时case: 2126753390
1702766719
看讨论发现是溢出了,所以改了下程序。
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); class Solution {
public:
int guessNumber(int n) {
int low=,high=n,g,r;
while(low<=high){
g=(low+high)/; //改成g=low+(high-low)/2;
r=guess(g);
if(r==-)high=g-;
else if(r==)low=g+;
else return g;
}
return ;
}
};
最新文章
- POJ - 2339 Rock, Scissors, Paper
- ng-view和ng-include之间的区别
- 电子工程师名片——FAT16文件系统
- jQuery + css 公告从左往右滚动
- hdu4725 The Shortest Path in Nya Graph
- 数据库中的null问题
- git 使用系列(一)—— git stash 的使用
- [技术] OIer的C++标准库 : 字符串库<;string>;
- QQ顶部的消息,联系人切换
- Netty学习笔记(二)
- CODING Pages 服务全面升级,更快更稳更可靠!
- [翻译] 使用 Python 创建你自己的 Shell:Part I
- mysql统计一年12月的数据
- Build 2017 Revisited: .NET, XAML, Visual Studio
- 利用ListView批量删除item
- 工欲善其事必先利其器,用Emmet提高HTML编写速度
- (源)VC助手VA破解使用指南
- python 展开嵌套的序列
- springboot学习入门之二---配置文件解析
- InsertionSort 直接插入排序(java)