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 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
update v2.0: class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; return pow(2, (round)(log(n) / log(2))) == n; } }; //如果没有考虑n <= 0就会超时。。 class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; while(n != 1) { if(n % 2 == 0) { n = n / 2; } else { return false; } } return true; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼