LeetCode:Power of Two - 2的冪

一、題目名稱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

相關文章
相關標籤/搜索