zoukankan      html  css  js  c++  java
  • 374. Guess Number Higher or Lower

    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 (-11, 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.
    题目含义:1到n里面选了一个数,让你来猜是哪一个。
    如果目标数比你猜的数小,返回-1,
    如果目标数比你猜的数大,返回1,
    如果两数相等,返回0

     1     public int guessNumber(int n) {
     2         if (guess(n) == 0) return n;
     3         int left = 1,right =n;
     4         while (left<right)
     5         {
     6             int mid = left + (right - left) / 2;
     7             int t = guess(mid);
     8             if (t == 0 )return mid;
     9             else if (t>0) left=mid;
    10             else right = mid;
    11         }
    12         return left;        
    13     }


  • 相关阅读:
    16款值得一用的iPhone线框图模板 (PSD & Sketch)
    设计神器
    {CF812}
    hiho1080(多标记线段树)
    {容斥原理}
    {dp入门}
    {AC自动机}
    CF807
    Trie树
    杂记
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7723653.html
Copyright © 2011-2022 走看看