如何在 C# 中判斷一個數字是否是 2 的冪次方?


2 的冪次方是指形式為 2n 的數,其中 n 為整數

以 2 為底數,以整數 n 為指數的指數運算結果。

n2n
01
12
24
38
416
532

示例 1

 執行演示

class Program {
   static void Main() {
      Console.WriteLine(IsPowerOfTwo(9223372036854775809));
      Console.WriteLine(IsPowerOfTwo(4));
      Console.ReadLine();
   }
   static bool IsPowerOfTwo(ulong x) {
      return x > 0 && (x & (x - 1)) == 0;
   }
}

輸出

False
True

示例 2

 執行演示

class Program {
   static void Main() {
      Console.WriteLine(IsPowerOfTwo(9223372036854775809));
      Console.WriteLine(IsPowerOfTwo(4));
      Console.ReadLine();
   }
   static bool IsPowerOfTwo(ulong n) {
      if (n == 0)
         return false;
      while (n != 1) {
         if (n % 2 != 0)
            return false;
         n = n / 2;
      }
      return true;
   }
}

輸出

False
True


更新時間: 2020-08-08

532 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.