C#中按位运算与相关算法题分享

994 阅读2分钟

& 按位与

public static void BitOperation()
{
    int a = 5;
    int b = 6;
    Console.WriteLine(a & b);
    Console.WriteLine("--------------");
    Console.WriteLine(Convert.ToString(a, 2));
    Console.WriteLine(Convert.ToString(b, 2));
    Console.WriteLine(Convert.ToString(a & b, 2));
}

| 按位或

^ 按位异或

结果排版问题,101与110异或下结果为011,即为11。

~ 按位取反

取反操作正数与负数区分操作,首先a为正数时,

        //假设操作数a = 5,(前4位为符号位) 
        //对应的其源码为:         0000 0101,
        //对源码取反得到:         1111 1010,    --得到负数,求出负数的补码
        //符号位不变,先取反:     1000 0101,
        //取反后再+1得出补码:     1000 0110,   --首位1代表-,即为-6

负数情况下,

        //假设操作数a = -5,(前4位为符号位)
        //对应的其源码为:        1111 1011,
        //对源码取反得到:        0000 0100,    --得到正数
        //正数的源码,反码,补码都是其本身   即为4

按位取反得简单算法: -(a + 1);

<< 按位左移

a = 5时二进制数据为0101,左移一位即为1010。

>> 按位右移

与左移同理,a = 5时二进制数据为0101,右移一位即为0010。

----------------------------------------------------分割线---------------------------------------------------

相关算法题分享

题目地址:leetcode-cn.com/problems/ha…

            public static int HammingDistance(int x, int y)
            {
                int count = 0;
                //通过按位异或得出二进制下的值
                string str = Convert.ToString(x ^ y, 2);     
                //计算字符串中1的数目即为所需的结果
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i].Equals('1')) count++;
                }
                return count;
            }

题目地址:leetcode-cn.com/problems/ma…

方法一:通过绝对值((a + b) + Math.Abs(a - b))/2

方法二:位运算

            public static int Maximum(int a, int b)
            {
                long aaa = ((long)a - (long)b) >> 63;
                int key = (int)(aaa & 1);
                return (key ^ 1) * a + key * b;
            }