Advertisement
1009. Complement of Base 10 Integer
EasyView on LeetCode
Time: O(log n)
Space: O(1)
Approach
Build a bitmask of all 1s with the same bit-length as n; XOR with n gives the complement.
1009.cs
C#
// Approach: Build a bitmask of all 1s with the same bit-length as n; XOR with n gives the complement.
// Time: O(log n) Space: O(1)
public class Solution
{
public int BitwiseComplement(int n)
{
int mask = 1;
while (mask < n)
mask = (mask << 1) + 1;
return mask ^ n;
}
}Advertisement
Was this solution helpful?