0
点赞
收藏
分享

微信扫一扫

LeetCode知识点总结 - 374

LeetCode 374. Guess Number Higher or Lower

考点难度
Binary SearchEasy
题目

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 will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns 3 possible results:

-1: The number I picked is lower than your guess (i.e. pick < num).
1: The number I picked is higher than your guess (i.e. pick > num).
0: The number I picked is equal to your guess (i.e. pick == num).
Return the number that I picked.

思路

Ternary Search: 把数分成三段,分别guess中间的两个节点,再根据结果缩小范围。

答案
public boolean isPowerOfThree(int n) {
        while(n>=3){
            if(n%3!=0) return false;
            n/=3;
        }
        return n==1;
    }
}
举报

相关推荐

0 条评论