Leetcode 3226. Number of Bit Changes to Make Two Integers Equal
You are given two integers, start
and goal
, and you need to determine the number of bit changes required to convert start
to goal
. A bit change means flipping a bit from 0 to 1 or from 1 to 0.
start
and goal
?
start
and goal
, as XOR between two bits results in 1 if they are different and 0 if they are the same.Integer.bitCount()
in Java.Here’s the implementation in Java:
public class BitChangeCounter {
public static int bitChangesToEqual(int start, int goal) {
// XOR the two numbers; different bits between two numbers will be 1
int xorResult = start ^ goal;
// Count the number of 1s in the binary representation of xorResult
return Integer.bitCount(xorResult);
}
public static void main(String[] args) {
int start = 29; // Example start value
int goal = 15; // Example goal value
System.out.println("Number of bit changes required: " + bitChangesToEqual(start, goal));
}
}
int xorResult = start ^ goal;
start
and goal
. Each bit in the result is 1 if the corresponding bits of start
and goal
differ.return Integer.bitCount(xorResult);
xorResult
. Integer.bitCount()
is a utility method in Java that efficiently counts the number of 1-bits.This solution is both efficient and straightforward due to the bitwise operations involved.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?