找 2 的次幂的正整数
求余法
int main()
{
int n
;
while (std
::cin
>> n
) {
while (n
% 2 == 0) {
n
= n
/ 2;
}
if (n
== 1) {
std
::cout
<< n
<< " yes" << std
::endl
;
} else {
std
::cout
<< n
<< " no" << std
::endl
;
}
}
}
位运算
int main()
{
int n
;
while (std
::cin
>> n
) {
if ((n
& (n
- 1)) == 0) {
std
::cout
<< n
<< " yes" << std
::endl
;
} else {
std
::cout
<< n
<< " no" << std
::endl
;
}
}
}
显然位运算更优秀,理解二进制是重点。
转载请注明原文地址:https://blackberry.8miu.com/read-44908.html