C++ 中十六進位制數字計數


給定一個具有起始和結束範圍的任務,計算給定範圍內的十六進位制數字或字母的數量。

什麼是十六進位制字母?

在計算機術語中,十六進位制數是指基數為 16 的數字,這意味著二進位制數字可以用 16 位表示。它包含從 0 到 15 的整數。其中 10 表示為 A,11 表示為 B,12 表示為 C,13 表示為 D,14 表示為 E,15 表示為 F。

因此,在下面的程式中,我們的任務是找到該範圍是否包含十六進位制字母。

例如

Input − start = 10, End = 13
Output − 4

說明 - 10 和 13 之間有 4 個十六進位制數字,即 10 為 A,11 為 B,12 為 C,13 為 D。

Input − start = 15, End = 16
Output − 1

說明 - 只有一個十六進位制字母,即 15 為 F,16 分別表示為 10。

下面程式中使用的的方法如下

  • 輸入從變數開始的範圍,假設為 start 和 end。

  • 宣告一個變數 count 來儲存計數並將其初始化為 0

  • 啟動一個 for 迴圈,從 i 開始,直到 i 小於或等於 end

  • 在迴圈內,檢查 i 是否大於或等於 10 且 i 也大於或等於 15,然後將 count 增加 1

  • 否則,檢查 i 是否大於 15

  • 然後,用 i 的值設定一個臨時變數 temp,並在 k 不等於 0 時遍歷

  • 並檢查 k%16 是否大於或等於 10

  • 將 count 增加 1

  • 並且,將 temp 設定為 temp/16

  • 返回 count 的值

  • 列印結果。

示例

 即時演示

#include <iostream>
using namespace std;
// Function to count the
// total number hexadecimal alphabet
int counthexa(int start, int end){
   int result = 0;
   for (int i = start; i <= end; i++){
      // All hexadecimal alphabets
      // from 10 to 15
      if (i >= 10 && i <= 15){
         result++;
      }
      // If i > 15 then perform mod by 16 repeatedly
      // till the number is > 0
      // If number % 16 > 10 then increase count
      else if (i > 15){
         int k = i;
         while (k != 0){
            if (k % 16 >= 10){
               result++;
            }
            k = k / 16;
         }
      }
   }
   return result;
}
// Main Function
int main(){
   int start = 10, end = 60;
   cout << "count is: "<<counthexa(start, end);
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

count is: 21

更新於:2020-05-15

297 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.