LeetCode icon indicating copy to clipboard operation
LeetCode copied to clipboard

c++ solution

Open mkn-root12 opened this issue 3 years ago • 0 comments

//time: O(log(N)! * log(N)), space: O(log(N)) class Solution { public: void swap(vector& nums, int i, int j){ int t = nums[i]; nums[i] = nums[j]; nums[j] = t; };

bool isPowerOf2(vector<int>& nums){
    if(nums[0] == 0) return false;
    
    int N = 0;
    for(int e : nums){
        N = N * 10 + e;
    }
    
    //the parenthesis around "N & 1" is required here!!
    while(N > 0 && ((N & 1) == 0)){
        N >>= 1;
    }
    
    return N == 1;
}

bool permutations(vector<int>& nums, int start){
    if(start == nums.size()){
        return isPowerOf2(nums);
    }
    
    for(int i = start; i < nums.size(); i++){
        swap(nums, start, i);
        
        if(permutations(nums, start+1))
            return true;
        
        swap(nums, start, i);
    }
    
    return false;
};

bool reorderedPowerOf2(int N) {
    vector<int> nums;
    while(N){
        nums.push_back(N%10);
        N /= 10;
    }
    
    return permutations(nums, 0);
}

};##3 @103style

mkn-root12 avatar Aug 26 '22 04:08 mkn-root12