![]() |
Given two numbers, A and B. Write a program to count the number of bits needed to be flipped to obtain B from A. Examples:
Below are the approaches to Count Number of Bits to be Flipped to Convert A to B using JavaScript: Table of Content Using the XOR operatorWe can use the XOR operator (^) to find the bits that are different between A and B. Then, we count the number of set bits (bits with value 1) in the result. Example: Implementation of a program to find the Number of bits to be flipped to obtain B from A using the XOR operator
Output Using XOR Operator: 4 Time Complexity: O(log(max(A, B))) Auxiliary Space: O(1) Using the AND operatorWe first Iterate through each bit of numbers A and B and than use AND operator to extract the least significant bit of A and B.If the bits are different, increment the flips count, and then right shift A and B to check the next bit. Example: Implementation of program to find Number of bits to flipped to obtain B from A using the AND operator
Output Using AND Operator: 4 Time Complexity: O(log(max(A, B))) Auxiliary Space: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |