A Java regex solution


  • 6
    W

    The binary string of power of 4 look like:
    "100"
    "10000"
    "1000000"

    There is always a "1" in the front, so we apply ^1 in regex.
    There is always a multiple of "00" in the rear, so we apply (00)+$.
    As a result, the total regex would look like ^1(00)+$.

    import java.util.regex.*;
    
    public class Solution {
        public boolean isPowerOfFour(int num) {
            
            if (num == 0) {
                return false;
            }
            
            String bString = Integer.toBinaryString(num);
            System.out.println(bString);
            
            String pattern = "^1(00)+$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(bString);
            return m.find();
        }
    }

  • 0

    The pattern should be "^1(00)*$" instead of "^1(00)+$" since it should return true with input 1.
    Here's the one line solution: return Pattern.matches("^1(00)*$", Integer.toBinaryString(num));


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.