Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c753d6c

Browse files
Create 3226. Number of Bit Changes to Make Two Integers Equal.cpp
1 parent aa73fc1 commit c753d6c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int minChanges(int n, int k) {
4+
if (n == k) return 0;
5+
string temp = "";
6+
while (n > 0) {
7+
int t = n & 1;
8+
temp.push_back(to_string(t)[0]);
9+
n = n >> 1;
10+
}
11+
string temp2 = "";
12+
while (k > 0) {
13+
int t = k & 1;
14+
temp2.push_back(to_string(t)[0]);
15+
k = k >> 1;
16+
}
17+
int ans = 0;
18+
int size = temp.size() - temp2.size();
19+
if (size < 0) return -1;
20+
string str = string(size, '0');
21+
temp2 += str;
22+
for (int i = 0; i < min(temp.size(), temp2.size()); i++) {
23+
if (temp[i] == '1' && temp2[i] == '0') ans++;
24+
else if (temp[i] == '0' && temp2[i] == '1') return -1;
25+
}
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /