Write a C function 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). So, doing n&(n-1) would give us the required result.

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%20%0A%2F*%20unsets%20the%20rightmost%20set%20bit%20of%20n%20and%20returns%20the%20result%20*%2F%0Aint%20fun(unsigned%20int%20n)%0A%7B%0A%20%20return%20n%26(n-1)%3B%0A%7D%20%20%20%20%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function%20*%2F%0Aint%20main()%0A%7B%0A%20%20int%20n%20%3D%207%3B%0A%20%20printf(%22The%20number%20after%20unsetting%20the%20rightmost%20set%20bit%20%25d%22%2C%20fun(n))%3B%0A%20%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/] [ad type=”banner”]

Categorized in: