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 231. Power of Two 解题报告

LeetCode 231. Power of Two 解题报告

LeetCode 326. Power of Three 解题报告

LeetCode 326. Power of Three 解题报告

Leetcode (4) Median of Two Sorted Arrays 解题报告

题目:Median of Two Sorted Arrays 找到两排序数组的全部元素的中位数。

LeetCode 421 Maximum XOR of Two Numbers in an Array 解题报告

一道有意思的题目, 用到了异或运算的一个小特性. LeetCode 421 Maximum XOR of Two Numbers in an Array. Given a non-empty arra...

LeetCode 350. Intersection of Two Array II 解题报告

LeetCode 350. Intersection of Two Array II 解题报告

[LeetCode] Median of Two Sorted Arrays 解题报告

—— write for my baby, mua [题目] There are two sorted arrays nums1 and nums2 of size m and n respe...

UVA 113 Power of Cryptography 解题报告

Power of Cryptography  Background Current work in cryptography involves (among other things) l...

Leetcode #21 Merge Two Sorted Lists 合并有序链表 解题报告

0 题外话嗯,从这次开始我就把题目换一下,改成解题报告了,因为我小节小结总是不分,等有时间也去改下之前的解题报告咯~~我算了下自己的速度,作为一个本学期的额外爱好,到现在21天刷了100题,速度也还算...
  • MebiuW
  • MebiuW
  • 2016年03月23日 20:54
  • 1014

[LeetCode] Add Two Numbers 解题报告

—— write for my baby, mua [题目] You are given two linked lists representing two non-negative numb...

[LeetCode] Two Sum 解题报告

—— write for my baby, mua [题目] Given an array of integers, return indices of the two numbers suc...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode解题报告233——Power of Two
举报原因:
原因补充:

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