Count Adjacent Bit Transitions
Given a positive integer n, consider its binary representation without leading zeros. Return the total number of adjacent bit transitions. An adjacent bit transition occurs whenever a 0 is immediately adjacent to a 1 or a 1 is immediately adjacent to a 0 in the binary sequence.
For example, if n = 13, its binary representation is "1101":
- Between the 1st bit (
1) and 2nd bit (1): no transition. - Between the 2nd bit (
1) and 3rd bit (0): 1 transition. - Between the 3rd bit (
0) and 4th bit (1): 1 transition.
Total transitions = 2.
[ "13" ]
Explanation. 13 in binary is '1101'. The bit transitions are from 1 to 0 and from 0 to 1, giving a total of 2 transitions.
[ "7" ]
Explanation. 7 in binary is '111'. All bits are equal, so there are 0 transitions.
[ "10" ]
Explanation. 10 in binary is '1010'. Every adjacent bit pair transitions between 1 and 0, giving a total of 3 transitions.
[ "1" ]
Explanation. 1 in binary is '1'. There are no adjacent bit pairs, so the answer is 0.
[ "43" ]
Explanation. 43 in binary is '101011'. The transitions occur at pairs (1,0), (0,1), (1,0), and (0,1), totaling 4 transitions.
[ "2" ]
Explanation. 2 in binary is '10'. There is 1 transition between the 1 and the 0.
Follow-up: Can you solve this in O(1) time complexity using bitwise operations such as XOR and bit shifting?
1 <= n <= 2^31 - 1