beats 88% and probably fastest C++ no-loop solution


  • 0
    J

    Let's embrace C++ 14...

    #include <unordered_set>
    
    constexpr bool not_exceed_int(unsigned int val) {
        return val * 3 <= INT_MAX;
    }
    
    template<int... ITEMS>
    struct ArrayHolder {
        static const std::unordered_set<int> value;
    };
    
    template<int... ITEMS>
    const std::unordered_set<int> ArrayHolder<ITEMS...>::value = {ITEMS...};
    
    template<bool CONDITION, int PREV_VAL, int... ITEMS>
    struct Maker {
        typedef typename
        Maker<not_exceed_int((unsigned int) PREV_VAL * 3), PREV_VAL * 3, PREV_VAL * 3, ITEMS...>::tunnel tunnel;
    };
    
    template<int PREV_VAL, int... ITEMS>
    struct Maker<false, PREV_VAL, ITEMS...> {
        typedef ArrayHolder<ITEMS...> tunnel;
    };
    
    class Solution {
    public:
        bool isPowerOfThree(int n) {
            typedef Maker<true, 1, 1>::tunnel tunnel;
            return tunnel::value.find(n) != tunnel::value.cend();
        }
    };
    

Log in to reply
 

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