\C# 程式旨在統計數字中的總位數


我們示例的數字為 11,即二進位制 −

1101

1101 中的總位數為 3;要找出它,請使用一個迴圈,直到它不等於 0。此處,我們的數字為 11,即十進位制 −

while (num>0) {
   cal += num & 1;
   num >>= 1;
}

示例

要統計數字中的總位數,請使用以下程式碼。

即時演示

using System;
public class Demo {
   public static void Main() {
      int cal = 0;
      // Binary is 1011
      int num = 11;
      while (num>0) {
         cal += num & 1;
         num >>= 1;
      }
      // 1 bits in 1101 are 3
      Console.WriteLine("Total bits: "+cal);
   }
}

輸出

Total bits: 3

更新於:19-6 月-2020

234 瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.