C++ constexpr solution


  • 0
    T

    This way we know the answer at compile time for constant values. For variable values, it will be computed at runtime.

    class Solution {
    public:
        constexpr bool uglyrecurse(int const num, bool const two, bool const three, bool const five)
        {
            return  (num == 0)     ? false                                  :
                    (num % 5 == 0) ? uglyrecurse(num / 5, two, three, true) :
                    (num % 3 == 0) ? uglyrecurse(num / 3, two, true, five)  :
                    (num % 2 == 0) ? uglyrecurse(num / 2, true, three, five):
                    (num == 1) ? (two || three || five)                     :
                    false;
        }
        
        constexpr bool isUgly(int num) {
            return ( num == 1 ) ? true : uglyrecurse(num, false, false, false);
        }
    };
    

Log in to reply
 

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