int main()
{
int n ;
std::cin >> n; // or scanf ("%d", &n);
int temp;
if(n ==1) temp = 1; // if n is 1 number is power of 2 so temp = 1
if(n % 2 != 0 && n!= 1) temp =0; // if n is odd it can't be power of two
else
{
for (;n && n%2 == 0; n /= 2);
if(n > 0 && n!= 1) temp = 0; // if the loop breaks out because of the second condition
else temp = 1;
}
std::cout << temp; // or printf ("%d", temp);
}
上面的代码检查一个数是否是2的幂。最坏的运行时复杂度是O(n)。如何通过降低时间复杂性来优化代码?降低时间复杂度
你的代码的运行时的复杂性在最坏的情况是O(log n)的你仍然可以做的更好(O(1))为如下所示 – CashCow 2011-01-25 10:12:53