-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3226.java
35 lines (34 loc) · 1.1 KB
/
_3226.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.fishercoder.solutions.fourththousand;
public class _3226 {
public static class Solution1 {
public int minChanges(int n, int k) {
if (n == k) {
return 0;
}
String nBin = Integer.toBinaryString(n);
String kBin = Integer.toBinaryString(k);
if (nBin.length() > kBin.length()) {
StringBuilder sb = new StringBuilder(kBin);
sb.reverse();
while (nBin.length() > sb.length()) {
sb.append("0");
}
kBin = sb.reverse().toString();
}
if (nBin.length() != kBin.length()) {
return -1;
}
int minChanges = 0;
for (int i = nBin.length() - 1; i >= 0; i--) {
if (nBin.charAt(i) != kBin.charAt(i)) {
if (nBin.charAt(i) == '1') {
minChanges++;
} else {
return -1;
}
}
}
return minChanges;
}
}
}