LeetCode-Power of 2, 3, 4

Title description:

Given an integer, write a function to determine whether it is a power of 2, 3, or 4.

Example 1:

  • Input: 1
  • Output: true
  • Explanation: 2^0 = 1

Calculating the power of 2 : problem-solving ideas

  • If n = 2^x and x is a natural number (that is, n is a power of 2), the following conditions must be met:
    • There is always n & (n-1) == 0, this is because:
      • n The highest binary bit is 1, and all other bits are 0;
      • n-1 The highest binary bit is 0, and all other bits are 1;
    • Must satisfy n> 0.
  • Therefore, we can determine whether n = 2^x is satisfied by n> 0 and n & (n-1) == 0.

code show as below:

class Solution {
    
    
    public boolean isPowerOfTwo(int n) {
    
    
        return n > 0 && (n & (n - 1)) == 0;
    }
}

Calculate the power of 3: violence

class Solution {
    
    
    public boolean isPowerOfThree(int n) {
    
    
        for (int i = 0; ; i++) {
    
    
            if (Math.pow(3, i) == n) {
    
    
                return true;
            }
            if (Math.pow(3, i) > n) {
    
    
                return false;
            }
        }
    }
}

Calculating the power of 4: problem-solving ideas

code show as below:

class Solution {
    
    
  public boolean isPowerOfFour(int num) {
    
    
    return (num > 0) && ((num & (num - 1)) == 0) && (num % 3 == 1);
  }
}

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114276029