C-Plus-Plus icon indicating copy to clipboard operation
C-Plus-Plus copied to clipboard

Turn off a particular bit in a number.

Open Gouriiseth opened this issue 2 years ago • 5 comments

Detailed description

Let's have a number n and a value k, we need to turn off the k'th bit in n numbers. Note: count starts from the rightmost bit in accordance with k. eg -> k=1 means the rightmost bit.

Input: n = 15, k = 1 Output: 14

Input: n = 14, k = 1 Output: 14 The rightmost bit was already off, so no change.

Context

By solving this problem, we can implement it in real life. As to find system failures due to some unavoidable resistor shutdowns or connection flaws.

Possible implementation

We can use bitwise operators like AND(&&) NOT(~) or Left Shift Operator(<<). Using expression ~(1<<(k-1)), we get a number that has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number that has all the bits the same as n except the k'th bit which is 0.

//below is the cpp implementation

#include <bits/stdc++.h> using namespace std;

// Returns a number that has all bits same as n // except the k'th bit which is made 0

int turnOffK(int n, int k) { // k must be greater than 0 if (k <= 0) return n;

// Do & of n with a number with all set bits except
// the k'th bit
return (n & ~(1 << (k - 1)));

}

// Driver program to test above function int main() { int n = 15; int k = 4; cout << turnOffK(n, k); return 0; }

Additional information

No response

Gouriiseth avatar Oct 14 '22 09:10 Gouriiseth

#2252 is the issue resolved by creating a bit manipulation question.

Gouriiseth avatar Oct 14 '22 09:10 Gouriiseth

can you assign this issue to me

BhavinSonagara avatar Oct 16 '22 07:10 BhavinSonagara

Can you assign this issue to me?

ishita126jain avatar Oct 19 '22 06:10 ishita126jain

can you assign this to me?

himanshukrabc avatar Oct 28 '22 13:10 himanshukrabc

can you assign this to me?

XxBeyonderxX avatar Oct 28 '22 15:10 XxBeyonderxX

This issue has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] avatar Jan 06 '23 00:01 github-actions[bot]

Please ping one of the maintainers once you add more information and updates here. If this is not the case and you need some help, feel free to ask for help in our Gitter channel or our Discord server. Thank you for your contributions!

github-actions[bot] avatar Jan 13 '23 00:01 github-actions[bot]