File tree Expand file tree Collapse file tree 3 files changed +181
-80
lines changed
LeetcodeProblemsTests/Algorithms/easy
LeetcodeProblems/Algorithms/easy Expand file tree Collapse file tree 3 files changed +181
-80
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 3226. Number of Bit Changes to Make Two Integers Equal
3+ https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal/description/
4+
5+ You are given two positive integers n and k.
6+
7+ You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
8+
9+ Return the number of changes needed to make n equal to k. If it is impossible, return -1.
10+
11+ Example 1:
12+
13+ Input: n = 13, k = 4
14+
15+ Output: 2
16+
17+ Explanation:
18+ Initially, the binary representations of n and k are n = (1101)base2 and k = (0100)base2.
19+ We can change the first and fourth bits of n. The resulting integer is n = (0100)base2 = k.
20+
21+
22+ Example 2:
23+
24+ Input: n = 21, k = 21
25+
26+ Output: 0
27+
28+ Explanation:
29+ n and k are already equal, so no changes are needed.
30+
31+ Example 3:
32+
33+ Input: n = 14, k = 13
34+
35+ Output: -1
36+
37+ Explanation:
38+ It is not possible to make n equal to k.
39+
40+ Constraints:
41+
42+ 1 <= n, k <= 10^6
43+
44+ */
45+
46+ /*
47+ Approach
48+ Check if transformation is possible:
49+
50+ Use a bitwise AND operation to ensure all 1 bits in k are also 1 bits in n. If not, return -1.
51+ Calculate the number of changes:
52+
53+ Use a bitwise XOR operation to identify differing bits between n and k.
54+ Count the number of 1s in the result of the XOR operation.
55+ */
56+
57+ /**
58+ * @param {number } n
59+ * @param {number } k
60+ * @return {number }
61+ */
62+ var minChanges = function bitChanges ( n , k ) {
63+ // Check if transformation is possible
64+ if ( ( n & k ) !== k ) {
65+ return - 1 ;
66+ }
67+
68+ // Calculate the number of changes
69+ let changes = 0 ;
70+ let diff = n ^ k ;
71+
72+ while ( diff > 0 ) {
73+ changes += diff & 1 ;
74+ diff >>= 1 ;
75+ }
76+
77+ return changes ;
78+ } ;
79+
80+ module . exports . minChanges = minChanges ;
Original file line number Diff line number Diff line change 1+ const assert = require ( "assert" ) ;
2+ const bitReverseToMakeNumberEqual = require ( "../../../LeetcodeProblems/Algorithms/easy/Bit_Reverse_To_Make_Numbers_Equal" ) . bitChanges ;
3+
4+
5+ function test ( ) {
6+ assert . deepEqual (
7+ bitChanges ( 13 , 4 ) ,
8+ 2
9+ ) ;
10+ assert . deepEqual (
11+ bitChanges ( 21 , 21 ) ,
12+ 0
13+ ) ;
14+ assert . deepEqual (
15+ bitChanges ( 14 , 13 ) ,
16+ - 1
17+ ) ;
18+ }
19+
20+ module . exports . test = test ;
You can’t perform that action at this time.
0 commit comments