[LeetCode] power of a power ➕ ➕ 231. 2 342. The power 4 326.3

1 Title Description

  1. Power of 2:
    Given an integer, write a function to determine whether it is a power of two.
  2. Power 3:
    Given an integer, write a function to determine whether it is a power of 3.
  3. Power 4:
    Given an integer (32-bit signed integer), write a function to determine whether it is a power of 4.

2 problem-solving ideas

  • Universal solution: - solving cycle

N let go cycle divided by the number to be determined, taking Cocycle judgment

For 2, the code is as follows:

class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n == 0){
            return false;
        }
        while(n % 2 ==0){
            n = n / 2;
        }
        return n == 1;


    }
}
  • Bit computing solution:
    for it is 2:
    shift operators: the binary number for about a shift. Left an expanded 2 times; right by 1 bit, 2-fold reduction.
return (n>0) && (1<<30) % n == 0;

Explanation: 1 << 30 maximum integer power of 2, if it is equal to 0 modulo n, only factor 2 n instructions.

For 3, the code follows

class Solution {
    public boolean isPowerOfThree(int n) {
        //3的幂次的质因子只有3,而所给出的n如果也是3的幂次,
        //故而题目中所给整数范围内最大的3的幂次的因子只能是3的幂次,
        //1162261467是3的19次幂,是整数范围内最大的3的幂次
        return (n >0 ) && (1162261467%n) == 0;

    }
}

3 resolution code

Solution 3 and 4 universal codes:

class Solution {
    public boolean isPowerOfThree(int n) {
        if(n == 0){
            return false;
        }
        while(n % 3 ==0){
            n = n / 3;
        }
        return n == 1;

    }
}
class Solution {
    public boolean isPowerOfFour(int num) {
        if(num == 0){
            return false;
        }
        while(num % 4 == 0){
            num = num/4;
        }
        return num == 1;

    }
}
Published 259 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43584847/article/details/104526012