Redian新闻
>
中兴做firefox手机了
avatar
中兴做firefox手机了# PDA - 掌中宝
S*h
1
最近做题做的有点晕的感觉... 这题我想的对么?
method1:
public boolean isPower2(int num){
if(num <= 0)
return false;
int mask = 1;
for(int i = 0; i <31; i++){
mask = mask << 1;
if(mask == num)
return true;
else if(mask > num)
return false;
}
return false;
}
method2:
public boolean isPower2(int num){
//skip
switch(num){
case 1:
case 2:
case 4:
...
case 2^30: return true;
default:return false;
}
}
avatar
q*x
3
bool isPower2(int num) {
return (num & (num -1) == 0);
}

【在 S****h 的大作中提到】
: 最近做题做的有点晕的感觉... 这题我想的对么?
: method1:
: public boolean isPower2(int num){
: if(num <= 0)
: return false;
: int mask = 1;
: for(int i = 0; i <31; i++){
: mask = mask << 1;
: if(mask == num)
: return true;

avatar
z*8
5
你这个没有考虑num=0

【在 q****x 的大作中提到】
: bool isPower2(int num) {
: return (num & (num -1) == 0);
: }

avatar
q*x
6
0是2的几次方?

【在 z*********8 的大作中提到】
: 你这个没有考虑num=0
avatar
l*a
7
you can also use ! to replace==0

【在 q****x 的大作中提到】
: bool isPower2(int num) {
: return (num & (num -1) == 0);
: }

avatar
z*8
8
都不是, 但是你的函数返回了true

【在 q****x 的大作中提到】
: 0是2的几次方?
avatar
S*h
9
沃勒歌曲..

【在 q****x 的大作中提到】
: bool isPower2(int num) {
: return (num & (num -1) == 0);
: }

avatar
l*a
10
http://graphics.stanford.edu/~seander/bithacks.html#DetermineIf
Determining if an integer is a power of 2
unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));

【在 q****x 的大作中提到】
: 0是2的几次方?
avatar
q*x
11
not good. better keep ! for bool only for better readability.
!b
i==0
p==NULL

【在 l*****a 的大作中提到】
: you can also use ! to replace==0
avatar
q*x
12
good catch!

【在 z*********8 的大作中提到】
: 都不是, 但是你的函数返回了true
avatar
q*x
13
i prefer:
return (n != 0) ? (n & (n-1) == 0) : false;

use:

【在 l*****a 的大作中提到】
: http://graphics.stanford.edu/~seander/bithacks.html#DetermineIf
: Determining if an integer is a power of 2
: unsigned int v; // we want to see if v is a power of 2
: bool f; // the result goes here
: f = (v & (v - 1)) == 0;
: Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
: f = v && !(v & (v - 1));

avatar
f*t
14
return !(n&(n-1));
avatar
S*I
15
(n > 0) for the condition.

【在 q****x 的大作中提到】
: i prefer:
: return (n != 0) ? (n & (n-1) == 0) : false;
:
: use:

avatar
S*I
16
! is valid for C/C++, not Java.

【在 l*****a 的大作中提到】
: you can also use ! to replace==0
avatar
q*x
17
good restriction.

【在 S**I 的大作中提到】
: ! is valid for C/C++, not Java.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。