位运算求绝对值

作者:追风剑情 发布于:2018-12-8 20:51 分类:Algorithms

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {

            int n = 5;
            Console.WriteLine(Abs(n));

            n = -5;
            Console.WriteLine(Abs(n));

            Console.Read();
        }

        public static int Abs(int x)
        {
            
            int y = x >> 31;

            Console.WriteLine("x: " + IntToBinary(x));
            Console.WriteLine("y: " + IntToBinary(y));
            Console.WriteLine("x^y: " + IntToBinary(x ^ y));
            Console.WriteLine("(x^y)-y: " + IntToBinary((x ^ y)-y));

            return (x ^ y) - y;
        }

        public static string IntToBinary(int val, int bits = 32)
        {
            string final = "";

            for (int i = bits; i > 0;)
            {
                if (i == 8 || i == 16 || i == 24) final += " ";
                final += ((val & (1 << --i)) != 0) ? '1' : '0';
            }
            return final;
        }
    }
}

运行测试

11111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号