今天看到别人在讨论如何快速判断2的N次方,自己也思考了下。这里汇总一下。
一、最快速的方法:
(number & number - 1) == 0
原因:因为2的N次方换算是二进制为10……0这样的形式(0除外)。与上自己-1的位数,这们得到结果为0。例如。8的二进制为1000;8-1=7,7的二进制为111。两者相与的结果为0。计算如下。
1000
& 0111
-------
0000
& 0111
-------
0000
代码:
//从textbox中取到数字
long number = long.Parse(txbNumber.Text);
/// <summary>
/// 使用“与”
/// </summary>
private void UseAndMethod()
{
if (number==1)
{
Response.Write("不是");
return;
}
string result = (number & number - 1).ToString();
if ((number & number - 1) == 0)
{
Response.Write("是");
}
else
{
Response.Write("不是");
}
}
long number = long.Parse(txbNumber.Text);
/// <summary>
/// 使用“与”
/// </summary>
private void UseAndMethod()
{
if (number==1)
{
Response.Write("不是");
return;
}
string result = (number & number - 1).ToString();
if ((number & number - 1) == 0)
{
Response.Write("是");
}
else
{
Response.Write("不是");
}
}
二、使用数学函数(没有第一个方法好)
//从textbox中取到数字
long number = long.Parse(txbNumber.Text);
/// <summary>
/// 使用Math.Log方法计算
/// </summary>
private void UseMathLog()
{
DateTime dtStart = DateTime.Now;
double power = Math.Log(number, 2);
long result = 0;
if (Int64.TryParse(power.ToString(), out result))
{
DateTime dtEnd = DateTime.Now;
Response.Write(number + "是2的" + power + "次方,花费时间为" + DateDiff(dtEnd, dtStart));
}
else
{
DateTime dtEnd = DateTime.Now;
Response.Write(number + "不是2的n次方," + "近接近的幂为:" + power + ",花费时间为" + DateDiff(dtEnd, dtStart));
}
}
long number = long.Parse(txbNumber.Text);
/// <summary>
/// 使用Math.Log方法计算
/// </summary>
private void UseMathLog()
{
DateTime dtStart = DateTime.Now;
double power = Math.Log(number, 2);
long result = 0;
if (Int64.TryParse(power.ToString(), out result))
{
DateTime dtEnd = DateTime.Now;
Response.Write(number + "是2的" + power + "次方,花费时间为" + DateDiff(dtEnd, dtStart));
}
else
{
DateTime dtEnd = DateTime.Now;
Response.Write(number + "不是2的n次方," + "近接近的幂为:" + power + ",花费时间为" + DateDiff(dtEnd, dtStart));
}
}
//计算时间
private string DateDiff(DateTime DateTimeEnd, DateTime DateTimeStart)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTimeEnd.Ticks);
TimeSpan ts2 = new TimeSpan(DateTimeStart.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.TotalMilliseconds.ToString() + "毫秒";
return dateDiff;
}
private string DateDiff(DateTime DateTimeEnd, DateTime DateTimeStart)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTimeEnd.Ticks);
TimeSpan ts2 = new TimeSpan(DateTimeStart.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.TotalMilliseconds.ToString() + "毫秒";
return dateDiff;
}
还有其它的一些算法。这里只列出两个。