Complete the function power_of_two/powerOfTwo (or equivalent, depending on your language) that determines if a given non-negative integer is a power of two. From the corresponding Wikipedia entry:
a power of two is a number of the form 2n where n is an integer, i.e. the result of exponentiation with number two as the base and integer n as the exponent.
You may assume the input is always valid.
(요약) 2
의 n
제곱수면 true
, 아니면 false
를 return
.
function isPowerOfTwo(n){ if(!n) return false; while(n > 1) { if(!(n % 2)) { n /= 2; } else { return false; } } return true; }
while
문을 이용해2
로 계속 나누다가 2로 안나눠지면false
를return
하고,
while
문이 끝나면2
의n
제곱수니까true
를return
.
0
은2
의n
제곱수가 아니라고 아예 나와서 첫 줄에서false
return
.