【第22期】观点:IT 行业加班,到底有没有价值?

leetcode解题报告233——Power of Two

原创 2015年07月08日 10:06:47

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

题目属于easy。前两种解法是一个意思,很容易想到;第三种解法最好(没想到)。

代码:

package bitmanipulation;

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

public class PowerofTwo {

    public boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        String s = Integer.toBinaryString(n);
        if (s.charAt(0) == '0') {
            return false;
        } else {
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i) == '1') {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isPowerOfTwo2(int n) {
        if (n <= 0) {
            return false;
        }
        while (n > 0) {
            if (n != 1 && n % 2 == 1) {
                return false;
            }
            n = n >> 1;
        }
        return true;
    }

    public boolean isPowerOfTwo3(int n) {
        if (n <= 0) {
            return false;
        }
        return (n & (n - 1)) == 0;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new PowerofTwo().isPowerOfTwo3(16));
    }

}
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

【LeetCode】Power of Two 解题报告

Power of Two[LeetCode]https://leetcode.com/problems/power-of-two/Total Accepted: 71172 Total Submiss...

[LeetCode]231.Power of Two

题目 Given an integer, write a function to determine if it is a power of two. 代码 /*--------------------------------------- * 日期:2015-08-0

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

【LeetCode】Power of Four 解题报告

Power of Four[LeetCode]https://leetcode.com/problems/power-of-four/Total Accepted: 9305 Total Submis...

[LeetCode]233.Number of Digit One

题目 Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. For example: Given n = 13,...

[leetcode] 233. Number of Digit One 解题报告

题目链接: https://leetcode.com/problems/number-of-digit-one/ Given an integer n, count the total numbe...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)