一、题目名称java
Power of Two (2的幂)code
二、题目地址leetcode
https://leetcode.com/problems/power-of-two开发
三、题目内容get
英文:Given an integer, write a function to determine if it is a power of two.it
中文:给出一个数字,判断它是不是2的乘方io
四、解题方法1function
最容易想到的方法,就是用输入的数字不断模除以2,为1则返回否,若是为0则继续作模除运算。class
Java代码以下:方法
/** * 功能说明:LeetCode 231 - Power of Two * 开发人员:Tsybius2014 * 开发时间:2015年8月22日 */ public class Solution { /** * 判断整数n是否为2的幂 * @param n 被考察数 * @return */ public boolean isPowerOfTwo(int n) { if (n <= 0) { return false; } while (n != 1) { if (n % 2 != 0) { return false; } else { n /= 2; } } return true; } }
四、解题方法2
一个更简单的方法是使用位运算完成:
/** * 功能说明:LeetCode 231 - Power of Two * 开发人员:Tsybius2014 * 开发时间:2015年8月22日 */ public class Solution { /** * 判断整数n是否为2的幂 * @param n 被考察数 * @return */ public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n-1)) == 0; } }
END