Isn't it easy?
To determine whether a number N is a power of 2, you only need to check whether N & (n-1) is 0.
To find the power of 2 that is larger than it, You can first fill the highest one of it with 1 and then add 1.
The filling method can be log32 = 5 times by bit or. In this way, branches do not have to be judged.
Maybe there is a faster and better way.
# Include < Cstdio >
Inline Bool Is_power_of_2 ( Int N)
{
Return(N&(N-1))= 0;
}
Inline Int Min_power_of_2_g ( Int N)
{
// Return n | = n> 16, N | = n> 8, N | = n> 4, N | = n> 2, N | = n> 1, n + 1; it is actually the same, it looks shorter.
Return (N | = N > 16 ) | = N > 8 ) | = N > 4 ) | = N > 2 ) | = N > 1 , N + 1 ;
}
Inline Int Min_power_of_2_eg ( Int N)
{
If(Is_power_of_2 (n ))
ReturnN;
ReturnMin_power_of_2_g (N );
}
Int Main ()
{
Int N;
While (Scanf ( " % D " , & N) = 1 )
{
N=Min_power_of_2_eg (N );
Printf ("% X % d \ n", N, N );
}
Return 0 ;
}
/**/ /* Here is the code generated by vc6 release:
MoV ECx, dword ptr [esp]; fetch n
MoV eax, ECx
Lea edX, [ecx-1]; n-1
Test ECx, EDX; n (n-1)
Je end1
SAR eax, 10 h; n | = n> 16
Or eax, ECx
MoV ECx, eax
SAR ECx, 8; n | = n> 8
Or eax, ECx
MoV edX, eax
SAR edX, 4; n | = n> 4
Or eax, EDX
MoV ECx, eax
SAR ECx, 2; n | = n> 2
Or eax, ECx
MoV edX, eax
SAR edX, 1; n | = n> 1
Or eax, EDX
INC eax; Add 1
End1:
*/