(13) Minimum Operations to Make the Integer Zero - LeetCode Contest

PHOTO EMBED

Sun Jun 25 2023 04:54:02 GMT+0000 (Coordinated Universal Time)

Saved by @DxBros #c++ #greedy

class Solution {
public:
    using ll = long long;
    int countBits(ll x){
        int cnt = 0;
        while(x > 0){
            cnt += (x&1);
            x>>=1;
        }
        return cnt;
    }
    int makeTheIntegerZero(int num1, int num2) {
        if(num1 < num2)
            return -1;
        ll x = num1;
        for(int i = 0; i <= 100; i++){
            ll val = x - (ll)i*num2;
            int cnt_ones = countBits(val);
            if(cnt_ones <= i && i <= val)
                return i;
        }
        return -1;
    }
};
content_copyCOPY

https://leetcode.com/contest/weekly-contest-351/problems/minimum-operations-to-make-the-integer-zero/