Beispiel #1
0
        // Time: O(n) where n is number of bits
        // Space: O(1)
        public static int GetPrevious(int n)
        {
            int temp = n;
            int trailingOnes = 0;
            int trailingZerosAfterOnes = 0;

            while ((temp & 1) == 1)
            {
                trailingOnes++;
                temp >>= 1;
            }

            while ((temp & 1) == 0 && temp != 0)
            {
                trailingZerosAfterOnes++;
                temp >>= 1;
            }

            if (trailingZerosAfterOnes == 0 ||
                trailingZerosAfterOnes + trailingOnes == 31)
            {
                return -1;
            }

            int rightMostNonTrailingOne = trailingZerosAfterOnes + trailingOnes;

            // Clear right most non trailing 1.
            n = BinaryHelpers.ClearBit(n, rightMostNonTrailingOne);

            // Set all ones below cleared bit.
            n |= (1 << rightMostNonTrailingOne) - 1;

            // Add back zeros in least significat bits.
            n &= -1 << (trailingZerosAfterOnes -1);

            return n;
        }