博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Guess Number Higher or Lower
阅读量:6852 次
发布时间:2019-06-26

本文共 1037 字,大约阅读时间需要 3 分钟。

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.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):-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it!Example:n = 10, I pick 6.Return 6.

 

 

/* The guess API is defined in the parent class GuessGame.   @param num, your guess   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0      int guess(int num); */public class Solution extends GuessGame {    public int guessNumber(int n) {        int l=1;        int r=n;        while(l<=r){            int m=l+((r-l)/2);            if(guess(m) == 1){                l=m+1;            }            else if(guess(m) == -1){                r=m-1;            }            else{                return m;            }        }        return -1;    }}

 

转载于:https://www.cnblogs.com/incrediblechangshuo/p/5686600.html

你可能感兴趣的文章
对于新手而言,PHP开发选择什么开发工具,及PhpStorm的特性和Git集成要点
查看>>
ebay 如何获取用户token
查看>>
LeetCode:Implement Queue using Stacks
查看>>
php 操作数组 (合并,拆分,追加,查找,删除等)
查看>>
CS50-线性搜索|二进制搜索
查看>>
iOS 图文混排 链接 可点击
查看>>
poj 1240
查看>>
UI设计时要注意的几个方面
查看>>
SVN 更新失败
查看>>
kmp循环节
查看>>
又撸了一上午的番
查看>>
学习笔记:Oracle 12C 数据非常规恢复工具bbed的使用说明
查看>>
保留CAAnimation执行后的效果
查看>>
第三方登录(QQ登录)开发流程详解
查看>>
Pwn2Own黑客大赛首日:Safari、IE8被攻破
查看>>
JSignature的使用
查看>>
批处理文件
查看>>
MySQL,Oracle,PostgreSQL,DB2,mongoDB,Hive, SAP HANA 数据库web维护客户端管理工具
查看>>
V-rep学习笔记:机器人模型创建1—模型简化
查看>>
cocos2dx simplegame 2 添加不同的怪物
查看>>