LeetCode #231 - Power of Two - Easy

来源:互联网 发布:mysql数据库设计 编辑:程序博客网 时间:2024/05/29 13:15

Problem

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

Example

Input: 2Output: true

Algorithm

整理一下题意:给定一个整数,判断其是否是2的幂。

简单判断即可。注意特殊情况,如负数,0,1。

代码如下。

class Solution {public:    bool isPowerOfTwo(int n) {        if(n<=0) return false;        bool isp=true;        while(n){            if(n%2==1&&n!=1){                isp=false;                break;            }            n/=2;        }        return isp;    }};
0 0
原创粉丝点击