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)。如何通过降低时间复杂度来优化代码?