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