位运算求绝对值

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

示例

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApp5
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12.  
  13. int n = 5;
  14. Console.WriteLine(Abs(n));
  15.  
  16. n = -5;
  17. Console.WriteLine(Abs(n));
  18.  
  19. Console.Read();
  20. }
  21.  
  22. public static int Abs(int x)
  23. {
  24. int y = x >> 31;
  25.  
  26. Console.WriteLine("x: " + IntToBinary(x));
  27. Console.WriteLine("y: " + IntToBinary(y));
  28. Console.WriteLine("x^y: " + IntToBinary(x ^ y));
  29. Console.WriteLine("(x^y)-y: " + IntToBinary((x ^ y)-y));
  30.  
  31. return (x ^ y) - y;
  32. }
  33.  
  34. public static string IntToBinary(int val, int bits = 32)
  35. {
  36. string final = "";
  37.  
  38. for (int i = bits; i > 0;)
  39. {
  40. if (i == 8 || i == 16 || i == 24) final += " ";
  41. final += ((val & (1 << --i)) != 0) ? '1' : '0';
  42. }
  43. return final;
  44. }
  45. }
  46. }

运行测试

11111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号