Skip to content

c++ solution  #4

Description

@mkn-root12

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions