[LeetCode]--342. Power of Four (Bit Manipulation)

    xiaoxiao2025-07-26  5

    1. Problem

    2. Loop Solution

    First, give my loop solution! Very easy!

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

    3. Bit Manipulation

    public class Solution { public boolean isPowerOfFour(int num) { return Integer.toBinaryString(num).matches("1(00)*"); } }

    Besides, in jdk1.8, we can use the code below!

    public boolean isPowerOfFour(int num) { return Integer.toString(num, 4).matches("10*"); }
    转载请注明原文地址: https://ju.6miu.com/read-1301090.html
    最新回复(0)