cs: add «2429. Minimize XOR»

URL:	https://leetcode.com/problems/minimize-xor/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-15 21:11:22 +01:00
parent 5af8d632b2
commit e02c4fda66
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

36
cs/minimize-xor.cs Normal file
View file

@ -0,0 +1,36 @@
public class Solution {
private int MostSignificantBit(int num) {
var mostSignificant = 0;
for (var mask = 1; mask <= num; mask <<= 1) {
if ((num & mask) != 0) {
mostSignificant = mask;
}
}
return mostSignificant;
}
public int MinimizeXor(int num1, int num2) {
var bitCount = int.PopCount(num2);
var mask = MostSignificantBit(num1);
var minimal = 0;
// Cancel out upper bits
for (; mask > 0 && bitCount > 0; mask >>= 1) {
if ((num1 & mask) != 0) {
minimal |= mask;
--bitCount;
}
}
// Add remaining bits from the “bottom”
for (mask = 1; bitCount > 0; mask <<= 1) {
if ((minimal & mask) == 0) {
minimal |= mask;
--bitCount;
}
}
return minimal;
}
}