Monday, September 9, 2019

342. power of four

342. power of four

https://leetcode.com/problems/power-of-four/

해결과정

10진수 to 2진수

  • 4 -> 100
  • 16 -> 10000
  • 64 -> 1000000
Runtime: 7 ms, faster than 5.74% of Java online submissions for Power of Four.
Memory Usage: 34.3 MB, less than 6.67% of Java online submissions for Power of Four.
public boolean isPowerOfFour(int num) {
        String binarySring = Integer.toBinaryString(num);
        if(binarySring.length()>=3 && (binarySring.length()-1)%2 ==0){
           return  "1".equals(binarySring.replaceAll("0", ""));
        }

        return false;
    }

second soluton

민수님 numberOfTrailingZero꺼랑 And 논리 연산자를 이용함.
100
011 의 and 0
class Solution {
    public boolean isPowerOfFour(int num) {
        if(num==0)return false;
        return Integer.numberOfTrailingZeros(num) % 2==0 && ((num & num-1) == 0);
    }
}

No comments:

Post a Comment