Alg*_*eek 2 c c++ algorithm time-complexity
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);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码检查数字是否为2的幂.最坏的情况是运行时复杂度为O(n).如何通过减少时间复杂度来优化代码?
Pra*_*rav 15
尝试if( n && (n & (n-1)) == 0) temp = 1;检查数字是否为2的幂.
例如 :
n = 16;
1 0 0 0 0 (n)
& 0 1 1 1 1 (n - 1)
_________
0 0 0 0 0 (yes)
Run Code Online (Sandbox Code Playgroud)
功率的数字2只有一位设置.
n & (n - 1) 取消最右边的设置位.
运行时间O(1);-)
正如@GMan注意到n需要是无符号整数.负有符号整数的按位运算是实现定义的.