leetcode筆記:Power of two,leetcodepower

來源:互聯網
上載者:User

leetcode筆記:Power of two,leetcodepower

一. 題目描述

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

二.題目分析

該題要求簡單,給定一個整數,判斷其是不是2的整數次冪,這道題的解題關鍵是找到一個規律:如果一個數字是2的整數次冪,若將該數寫為位元,這個位元中有且僅有一位為1,其餘均為0。根據這一性質,不難給出以下給出兩種解決方案。

三.範例程式碼

// 將n不停右移,比較位元中1出現的個數,count = 1時判定為turebool isPowerOfTwo(int n) {      int count = 0;      while (n > 0)      {          count+=(n&0x01);           n>>=1;      }      if(sum==1)        return true;    else        return false;}

以下方法同樣利用了一個2的整數次冪的二進位寫法中有且僅有一位為1的性質。假設該數為n,根據這一性質,則(n - 1)必然是將n的最高位1置0,然後其餘二進位位均置1,若且唯若這種情況下,有(n&(n-1)) == 0,一個例子:

n = 8 -> 1000
n - 1 = 7 -> 0111
則有:1000 & 0111 = 0000

class Solution {  public:      bool isPowerOfTwo(int n) {          return (n>0) && (!(n&(n-1)));      }  };  

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.