JavaScript - Turn off the kth bit of a given number
JavaScript Bit Manipulation: Exercise-9 with Solution
Write a JavaScript program to turn off the kth bit in a given number. Return the updated number.
Test Data:
(30, 3)-> 26
Explanation:
Binary format of 30 is -> 11110
Fortmat of the said number after off the 3rd bit -> 11010
After converting 11010 to decimal : 11010 -> 26
(100, 6) -> 68
Explanation:
Binary format of 100 is -> 1100100
Fortmat of the said number after off the 6th bit -> 1000100
After converting 1000100 to decimal : 1000100 -> 68
Sample Solution:
JavaScript Code:
// Define a function to turn off the kth bit of a number
const turn_Off_Kth_Bit = (n, k) => {
// Check if the input is not a number
if (typeof n != "number") {
return 'It must be number!'; // Return an error message
}
// Return the result of performing a bitwise AND operation with the complement of the kth bit
return n & ~(1 << (k - 1));
}
// Initialize variables n and k with values
let n = 30;
let k = 3;
// Display the binary representation of n
console.log(n + " in binary is " + n.toString(2));
console.log("Turning k'th bit off," + " k = " + k);
// Call the turn_Off_Kth_Bit function and display the result
let result_n = turn_Off_Kth_Bit(n, k);
console.log(result_n + " in binary is " + result_n.toString(2));
// Update variables n and k with new values
n = 100;
k = 6;
// Display the binary representation of n
console.log(n + " in binary is " + n.toString(2));
console.log("Turning k'th bit off," + " k = " + k);
// Call the turn_Off_Kth_Bit function and display the result
result_n = turn_Off_Kth_Bit(n, k);
console.log(result_n + " in binary is " + result_n.toString(2));
Output:
30 in binary is 11110 Turning k'th bit off, k = 3 26 in binary is 11010 100 in binary is 1100100 Turning k'th bit off, k = 6 68 in binary is 1000100
Flowchart:
Live Demo:
See the Pen javascript-bit-manipulation-exercise-9 by w3resource (@w3resource) on CodePen.
* To run the code mouse over on Result panel and click on 'RERUN' button.*
Improve this sample solution and post your code through Disqus.
Previous: Binary logarithm using bitwise operators.
Next: Turn on the kth bit of a given number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/bit-manipulation/bit-manipulation-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics