1. 程式人生 > >LeetCode(52) Power of Two

LeetCode(52) Power of Two

題目描述

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

本題要求判斷一個數是否是2的指數。

題目解答

本題很簡單可以通過位運算進行判斷。首先如果一個數為負,則肯定不為2的指數,直接返回false;對於正數可以判斷該數字二進位制表達時1的個數,如果1的個數為只有一個則為2的指數,否則不為2的指數。

當然本題也可以通過不停的對待判斷數字除以2,若最終為1,則說明該數字是2的指數。

class Solution {
public:

    bool isPowerOfTwo(int
n) { if(n <= 0) return false; int count = 0; const int one = 1; while(n) { if(n & one == one) count++; n = n >> 1; } if(count == 1) return true; else return false; } };