Skip to content

Commit b11d3c9

Browse files
authored
Add 2429_Minimize_XOR.py (#63)
* Added solution for 2429. Minimize XOR with Python3 Contributed by @LONGNEW
1 parent 81abc9f commit b11d3c9

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ I'm currently working on [Analytics-Zoo](https://github.com/intel-analytics/anal
246246
| 1981 | [Minimize the Difference Between Target and Chosen Elements](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/) | [Java](https://github.com/qiyuangong/leetcode/blob/master/java/1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java) | DP memo[row][sum] to avoid recomputing |
247247
| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2409_Count_Days_Spent_Together.py)| Use month as a day |
248248
| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2413_Smallest_Even_Multiple.py)| Check the n is multiply by 2 |
249+
| 2429 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | [Python](https://github.com/qiyuangong/leetcode/blob/master/python/2429_Minimize_XOR.py.py) | check the num1, num2 with length and replace "0" compare with num1. |
249250

250251
| # | To Understand |
251252
|---| ----- |

python/2429_Minimize_XOR.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution:
2+
def minimizeXor(self, num1: int, num2: int) -> int:
3+
# remove "0b" in front of num1, num2
4+
num1, num2 = bin(num1)[2:], bin(num2)[2:]
5+
lenNum1, lenNum2 = len(num1), len(num2)
6+
ones = num2.count("1")
7+
maxLen = max(lenNum1, lenNum2)
8+
9+
# ans list have elements same as the maxLen
10+
ans = []
11+
for _ in range(maxLen):
12+
ans.append("0")
13+
14+
# add "0" in front of the binary numbers to make indexing easier
15+
for _ in range(maxLen - lenNum1):
16+
num1 = "0" + num1
17+
18+
for _ in range(maxLen - lenNum2):
19+
num2 = "0" + num2
20+
21+
# now make "x XOR num1" minimal
22+
# fill the ans list from index "0"
23+
# because XOR give 0 when the elements are same.
24+
for i in range(len(num1)):
25+
if num1[i] == "1" and ones:
26+
ans[i] = "1"
27+
ones -= 1
28+
29+
# if we still got "1" to fill in the ans list.
30+
# "1" need to be fill from the back of ans list.
31+
# to maintain the number small.
32+
for i in range(len(ans) - 1, -1, -1):
33+
if ones < 1:
34+
break
35+
36+
if ans[i] == "1":
37+
continue
38+
39+
ans[i] = "1"
40+
ones -= 1
41+
42+
# make the ans in string
43+
ans = "".join(ans)
44+
return int(ans, 2)

0 commit comments

Comments
 (0)