using readable C++ constexpr function to replace magic number


  • 0
    J
    constexpr bool not_exceed_int(unsigned val) {
        return val <= INT_MAX;
    }
    
    constexpr int and_odd_power_of_2(int mask = 0b10, unsigned int prev_val = 0b10) {
        return not_exceed_int(prev_val << 2) ?
               and_odd_power_of_2(mask | prev_val << 2, prev_val << 2) : mask;
    }
    
    class Solution {
    public:
        bool isPowerOfFour(int num) {
            return num > 0 && (num & (num - 1)) == 0 /* should be power of 2, i.e. 0b10 0b100... */
                   && (num & and_odd_power_of_2()) == 0; /* should not be odd power of 2, i.e. 0b1000(2^3)... */
        }
    };
    

Log in to reply
 

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