Check each Bit | C++, Python, Java
Approach\n Describe your approach to solving the problem. \nIterate through all the bits in n. Dividing an integer by two is the same as shifting all the bits t
# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate through all the bits in `n`. Dividing an integer by two is the same as shifting all the bits to the right once, therefore we can use its parity (`n % 2`) for the value of the rightmost bit.\n\nSince we can only change ones in `n` to zeros, if a bit is zero in `n` but one in `k`, then we can return -1 from here. Otherwise, we increment `res` if the bit is a one in `n` and a zero in `k`.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n    int minChanges(int n, int k) {\n        int res = 0;\n        while (n || k){\n            if (n % 2 == 0 && k % 2)\n                return -1;\n            else if (n % 2 != k % 2)\n                res++;\n            n /= 2;\n            k /= 2;\n        }\n        return res;\n    }\n};\n```\n```python []\nclass Solution:\n    def minChanges(self, n: int, k: int) -> int:\n        res = 0\n        while n or k:\n            if n % 2 == 0 and k % 2:\n                return -1\n            elif n % 2 != k % 2:\n                res += 1\n            n //= 2\n            k //= 2\n        return res\n```\n```Java []\nclass Solution {\n    public int minChanges(int n, int k) {\n        int res = 0;\n        while (n != 0 || k != 0){\n            if (n % 2 == 0 && k % 2 == 1)\n                return -1;\n            else if (n % 2 != k % 2)\n                res++;\n            n /= 2;\n            k /= 2;\n        }\n        return res;\n    }\n}\n```\n
['Bit Manipulation', 'C', 'Python', 'C++', 'Java', 'Python3']