Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created November 8, 2025 18:46
Show Gist options
  • Select an option

  • Save tatsuyax25/aab1db1d1001e436ebfc2d95c0605876 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/aab1db1d1001e436ebfc2d95c0605876 to your computer and use it in GitHub Desktop.
Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to
/**
* Calculates the minimum number of operations to reduce a number `n` to 0
* using a specific bitwise operation rule:
* - You can flip the lowest 1-bit and all bits to its right.
*
* This function uses a recursive approach based on the properties of Gray code.
*
* @param {number} n - The input number.
* @return {number} - Minimum number of operations to reduce `n` to 0.
*/
var minimumOneBitOperations = function(n) {
// Base case: if n is 0 or 1, return n directly
if (n <= 1) return n;
// Find the position of the highest set bit in `n`
let highestBit = 0;
while ((1 << highestBit) <= n) {
highestBit++;
}
// Compute the value of the highest bit (2^(highestBit - 1))
const highestBitValue = 1 << (highestBit - 1);
// Recursive step:
// - Flip all bits below the highest bit (which gives (2^k - 1) operations)
// - Then recursively reduce the remaining part: n - 2^(k-1)
return ((1 << highestBit) - 1) - minimumOneBitOperations(n - highestBitValue);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment