leetcode [#231]

目录

题目

Given an integer, write a function to determine if it is a power of two.


解决方案

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n < 0) return false;
if(n == 1) return true;
double n1 = (double) n;
while (n1 / 2.0 >= 1.0) {
n1 = n1 / 2.0;
}
return n1 == 1.0 ? true : false;
}
}

注意事项

  1. 先处理特殊情况。
  2. 将n转换为double型,不断除以2,直到结果小于1.0.此时根据n1的结果即可确定。