isPowerOfTwo

//Given an integer, write a function to determine if it is a power of two.
public class isPowerOfTwo {
    public static boolean isPowerOfTwo(int n) {
        if (n == 1)
            return true;
        else if (n < 0)
            return false;
        else {
            String str = Integer.toBinaryString(n);
            for(int i=1;i<str.length();i++)
            {
                if(‘1‘==str.charAt(i))
                    return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
      System.out.println(isPowerOfTwo(1024));

    }
}
时间: 2025-01-02 04:22:45

isPowerOfTwo的相关文章

231.是否为2的平方根 IsPowerOfTwo

Power of Two Total Accepted: 3596 Total Submissions: 11779 Given an integer, write a function to determine if it is a power of two. Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. [思路] 如果是power of t

ispoweroftwo 判断2的次幂【转】

转自:https://www.cnblogs.com/troublelost/p/5236391.html 首先结果是: public bool IsPowerOfTwo(int n) { if(n<1) return false;//2的次幂一定大于0 return ((n & (n -1)) == 0); } 分析:2的次幂在计算机中可以用左移(<<)来运算,了解n&(n-1)的作用如下: n&(n-1)作用:将n的二进制表示中的最低位为1的改为0,先看一个简

leetcode 231. Power of Two

Given an integer, write a function to determine if it is a power of two. class Solution { public: bool isPowerOfTwo(int n) { int num = 0; while (n > 0) { if (n &1) num++; n/=2; } if (num == 1) return true; return false; } };

[LeetCode] Power of Two

Given an integer, write a function to determine if it is a power of two. 判断一个整数是否是2的幂.如果一个数是2的幂,则这个数的二进制表示中,最高位是1,其他位都是0.这个数-1的二进制位全是1.所以我们可以利用这个规律对两个数取与进行判断. class Solution { public: bool isPowerOfTwo(int n) { if (n <= 0) return false; return !(n &

[LeetCode]Reverse Bits

题目:Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through thi

Unity3d学习笔记(持续更新)。。。

[转]自http://blog.csdn.net/quannenggou/article/details/7204172 Mathf 数学运算 Mathf.Abs绝对值 计算并返回指定参数 f 绝对值. Mathf.Acos反余弦 static function Acos (f : float) : float 以弧度为单位计算并返回参数 f 中指定的数字的反余弦值. Mathf.Approximately近似 static function Approximately (a : float,

231. Power of Two

题目: Given an integer, write a function to determine if it is a power of two. 答案: 2的幂有两个特点: 1)大于0 2)二进制形式都是首位为1,其余位为0,因此n&(n-1)等于0 1 class Solution { 2 public: 3 bool isPowerOfTwo(int n) { 4 if( n>0&&(!(n&(n-1))) ) 5 return true; 6 else

Power of Two

Given an integer, write a function to determine if it is a power of two. 2的幂数二进制只有一个1 1 bool isPowerOfTwo(int n) { 2 if(n <= 0) 3 return 0; 4 return (n & (n-1)) == 0; 5 }

Unity API - C

废话不多说,一针见血,go! 一起来看 API Caching 缓存 Camera 摄像机 CapsuleCollider 胶囊碰撞器 CharacterController 角色控制器 CharacterJoint 角色关节 Cloth 布料 ClothRenderer 布料渲染器 ClothSkinningCoefficient 布料蒙皮系数 Collider 碰撞器 Collision 碰撞 Color 颜色 CombineInstance 合并实例 Caching 缓存 Caching.