2
头图

Power of 2

Title description: Give you an integer n, please judge whether the integer is a power of 2. If yes, return true; otherwise, return false.

If there is an integer x such that n == $2^{x}$, then n is considered to be a power of 2.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/power-of-two/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Dichotomy

First, if n is negative, return false directly;

Then use the dichotomy to find out whether there is an integer that meets the conditions, minPower and maxPower are the smallest and largest powers of 2 in the integer range, the process is as follows:

  • mid is assigned as the middle value of maxPower and minPower;
  • Determine if the mid power of 2 is equal to n, then return true;
  • If the mid power of 2 is greater than n, assign maxPower to mid-1;
  • If the mid power of 2 is less than you, assign minPower to mid+1;
  • The condition for the termination of the loop is that minPower is greater than maxPower.

Finally, if there is no qualified integer, return false.

public class LeetCode_231 {
    public static boolean isPowerOfTwo(int n) {
        if (n < 0) {
            return false;
        }
        int minPower = 0, maxPower = 30, mid;
        while (minPower <= maxPower) {
            mid = (minPower + maxPower) / 2;
            if (n == Math.pow(2, mid)) {
                return true;
            } else if (n < Math.pow(2, mid)) {
                maxPower = mid - 1;
            } else {
                minPower = mid + 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16));
    }
}
[Daily Message] The rudder to control fate is struggle, without a trace of illusion, without giving up a little opportunity, and without stopping one day's hard work.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!