Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

c++ solution #4

Open
mkn-root12 opened this issue Aug 26, 2022 · 0 comments
Open

c++ solution #4

mkn-root12 opened this issue Aug 26, 2022 · 0 comments

Comments

@mkn-root12
Copy link

//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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant