跳至主要内容

3226. Number of Bit Changes to Make Two Integers Equal

class Solution {
public:
int minChanges(int n, int k)
{
if (n == k) return 0;

string n1 = bitset<32>(n).to_string();
string k1 = bitset<32>(k).to_string();

int cnt = 0;
for (int i = 0; i < 32; i++)
{
if (n1[i] != k1[i] && n1[i] == '0') return -1;
else if (n1[i] != k1[i] && n1[i] == '1') ++cnt;
}
return cnt;
}
};
  • T: O(1)O(1)
  • S: O(1)O(1)