コード例 #1
0
ファイル: Question_5_4.cs プロジェクト: jkrez/Interview
        // Time: O(n) where n is number of bits
        // Space: O(1)
        public static int GetNext(int n)
        {
            int temp = n;
            int trailingZeros = 0;
            int trailingOnesAfterZero = 0;
            while (((temp & 1) == 0) && (temp != 0))
            {
                trailingZeros++;
                temp >>= 1;
            }

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

            if (trailingOnesAfterZero + trailingZeros == 0 ||
                trailingOnesAfterZero + trailingZeros == 31)
            {
                return -1;
            }

            int rightMostNonTralingZero = trailingOnesAfterZero + trailingZeros;

            // Flip rightMostNonTralingZero.
            n = BinaryHelpers.SetBit(n, rightMostNonTralingZero);

            // Clear all bits below fliped bit.
            n &= ~((1 << rightMostNonTralingZero) - 1);

            // Add back in number of ones cleared.
            n |= (1 << (trailingOnesAfterZero - 1)) - 1;

            return n;
        }