思考
有的很常见的方法思维,虽然在99% 的情况下不会出错,但是仍然会有 1% 的情况会出错,往为了这 1% 去思考不同的解决方案
方法实现
/// <summary>
/// 【方法1】计算两个数的平均值,此方法存在数据上下限溢出的情况
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int Average1(int x, int y) => (x + y) / 2;
/// <summary>
/// 【方法2】计算两个数的平均值,此方法比较正常,好用
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int Average2(int x, int y) => x + (y - x) / 2;
/// <summary>
/// 【方法3】计算两个数的平均值,此方法比较正常,好用
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int Average3(int x, int y) => x + ((y - x) >> 1);
/// <summary>
/// 【方法4】计算两个数的平均值,采用位运算 - 交集加上差集的一半(向下取整)
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int Average4(int x, int y) => (x & y) + ((x ^ y) >> 1);
/// <summary>
/// 【方法5】计算两个数的平均值,采用位运算 - 交集加上差集的一半(向上取整)
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int Average5(int x, int y) => (x | y) - ((x ^ y) >> 1);
static void Main(string[] args)
{
var intMin = int.MinValue; // -2147483648
var intMax = int.MaxValue; // 2147483647
var int50 = 50;
var int50b = -50;
var intNum4 = 4;
var intNum5 = 5;
var resultAverage1_1 = Average1(intMin, intMin); // 0
var resultAverage1_2 = Average1(intMax, intMax); // -1
var resultAverage1_3 = Average1(int50, int50); // 50
var resultAverage1_4 = Average1(int50b, int50b); // -50
var resultAverage1_5 = Average1(intNum4, intNum5); // 4
var resultAverage2_1 = Average2(intMin, intMin); // -2147483648
var resultAverage2_2 = Average2(intMax, intMax); // 2147483647
var resultAverage2_3 = Average2(int50, int50); // 50
var resultAverage2_4 = Average2(int50b, int50b); // -50
var resultAverage2_5 = Average2(intNum4, intNum5); // 4
var resultAverage3_1 = Average3(intMin, intMin); // -2147483648
var resultAverage3_2 = Average3(intMax, intMax); // 2147483647
var resultAverage3_3 = Average3(int50, int50); // 50
var resultAverage3_4 = Average3(int50b, int50b); // -50
var resultAverage3_5 = Average3(intNum4, intNum5); // 4
var resultAverage4_1 = Average4(intMin, intMin); // -2147483648
var resultAverage4_2 = Average4(intMax, intMax); // 2147483647
var resultAverage4_3 = Average4(int50, int50); // 50
var resultAverage4_4 = Average4(int50b, int50b); // -50
var resultAverage4_5 = Average4(intNum4, intNum5); // 4
var resultAverage5_1 = Average5(intMin, intMin); // -2147483648
var resultAverage5_2 = Average5(intMax, intMax); // 2147483647
var resultAverage5_3 = Average5(int50, int50); // 50
var resultAverage5_4 = Average5(int50b, int50b); // -50
var resultAverage5_5 = Average5(intNum4, intNum5); // 5
}
参考文章
位运算的妙用-求两个整数的平均值 - 知乎
https://zhuanlan.zhihu.com/p/134225899
计算两个数的平均值几种方法_二个数字怎么求平均值的公式-CSDN博客
https://blog.csdn.net/qq_36942720/article/details/121042778
发表评论