【LeetCode】(231)Power of Two(Easy)

来源:互联网 发布:酷狗音乐数据异常 编辑:程序博客网 时间:2024/06/01 15:38

题目

Power of Two

 Total Accepted: 21194 Total Submissions: 70828My Submissions

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





解析

超级简单,每次判断是否能被2除,可以的话就除以2继续循环。考虑负数和1的情况。

class Solution {public:    bool isPowerOfTwo(int n) {        if (n == 1) { return true; } if (n <= 0) { return false; } while (n != 1) { if (n%2 != 0) { return false; } else { n = n/2; } } return true;    }};













0 0
原创粉丝点击