2023-11-30 Daily Challenge
Today I have done leetcode's November LeetCoding Challenge with cpp
.
November LeetCoding Challenge 30
Description
Minimum One Bit Operations to Make Integers Zero
Given an integer n
, you must transform it into 0
using the following operations any number of times:
- Change the rightmost (
0th
) bit in the binary representation ofn
. - Change the
ith
bit in the binary representation ofn
if the(i-1)th
bit is set to1
and the(i-2)th
through0th
bits are set to0
.
Return the minimum number of operations to transform n
into 0
.
Example 1:
Input: n = 3 Output: 2 Explanation: The binary representation of 3 is "11". "11" -> "01" with the 2nd operation since the 0th bit is 1. "01" -> "00" with the 1st operation.
Example 2:
Input: n = 6 Output: 4 Explanation: The binary representation of 6 is "110". "110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010" -> "011" with the 1st operation. "011" -> "001" with the 2nd operation since the 0th bit is 1. "001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109
Solution
class Solution {
public:
int minimumOneBitOperations(int n) {
int res = 0;
while(n > 0) {
res = -(res + (n ^ (n - 1)));
n &= n - 1;
}
return abs(res);
}
};
// Accepted
// 308/308 cases passed (3 ms)
// Your runtime beats 45.97 % of cpp submissions
// Your memory usage beats 80.09 % of cpp submissions (6.2 MB)