Turn off the rightmost set bit

Write a program that unsets the rightmost set bit of an integer.
Examples :

Input: 12 (00…01100)
Output: 8 (00…01000)

Input: 7 (00…00111)
Output: 6 (00…00110)

Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit (including the set bit). We can get x3.5 by adding 2 x, x and x/2. To calculate 2x, left shift x by 1 and to calculate x/2, right shift x by 2. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. Write a program to subtract one from a given number. The idea is to use bitwise operators. Like addition, Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. The use of operators like ‘+’, ‘-‘, ‘ ’, ‘/’, ‘++’, ‘–‘ …etc. are not allowed. So, doing n&(n-1) would give us the required result.

  • Implementation

using System;

class GFG {

/* unsets the rightmost set bit

of n and returns the result */

static int fun( int n)

{

return n & (n - 1);

}

// Driver code

public static void Main()

{

int n = 7;

Console.Write( "The number after unsetting "

+ "the rightmost set bit " + fun(n));

}

}

Output :

The number after unsetting the rightmost set bit 6