CodeWars 코딩 문제 2021/01/26 - Power of two

이호현·2021년 1월 25일
1

Algorithm

목록 보기
65/138

[문제]

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.

(요약) 2n제곱수면 true, 아니면 falsereturn.

[풀이]

function isPowerOfTwo(n){
  if(!n) return false;

  while(n > 1) {
    if(!(n % 2)) {
      n /= 2;
    }
    else {
      return false;
    }
  }

  return true;
}

while문을 이용해 2로 계속 나누다가 2로 안나눠지면 falsereturn하고,
while문이 끝나면 2n제곱수니까 truereturn.
02n제곱수가 아니라고 아예 나와서 첫 줄에서 false return.

profile
평생 개발자로 살고싶습니다

0개의 댓글