Minimum Bit Flips to Convert Number

Bit Manipulation Problems Medium

Given two integers start and goal. Flip the minimum number of bits of start integer to convert it into goal integer.


A bits flip in the number val is to choose any bit in binary representation of val and flipping it from either 0 to 1 or 1 to 0.

Examples:

Input : start = 10 , goal = 7

Output : 3

Explanation : The binary representation of 10 is "1010".

The binary representation of 7 is "111".

If we flip the underlined bits in binary representation of 10 then we will obtain our goal.

Input : start = 3 , goal = 4

Output : 3

Explanation : The binary representation of 3 is "011".

The binary representation of 4 is "100".

So if we flip all the three bits of 3 then we will reach our goal number.

Input : start = 1 , goal = 7

Constraints

  • 1 <= start , end <= 109

Hints

  • To convert start to goal, XOR the two integers. The result of XOR will have 1s at all the bit positions where start and goal differ.
  • "Count the number of 1s in the XOR result. Each 1 corresponds to a bit that needs to be flipped to convert start into goal. This count gives the minimum number of bit flips required. "

Company Tags

Reddit Ernst & Young Flipkart American Express Byju's Morgan Stanley Walmart Airbnb Optum Databricks Swiggy Roche DoorDash IBM HCL Technologies Stripe NVIDIA Johnson & Johnson Zomato ARM McKinsey & Company Twilio Boston Consulting Group MongoDB Electronic Arts Google Microsoft Amazon Meta Apple Netflix Adobe