C-Plus-Plus
C-Plus-Plus copied to clipboard
Turn off a particular bit in a number.
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
#2252 is the issue resolved by creating a bit manipulation question.
can you assign this issue to me
Can you assign this issue to me?
can you assign this to me?
can you assign this to me?
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.
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!