C++中整數奇偶數位計數


給定一個整數,任務是計算其中偶數位和奇數位的個數。此外,我們還需要檢查整數中的偶數位是否出現偶數次,以及奇數位是否出現奇數次。

例如

Input − digit = 12345
Output − count for even digits = 2
      count for odd digits = 3

說明 − 是的,偶數位出現偶數次(即2次),奇數位出現奇數次(即3次)。

Input − digit = 44556
Output − count for even digits = 3
      count for odd digits = 2

說明:否,因為偶數位出現奇數次(即3次),奇數位出現偶數次(即2次)。

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

  • 輸入一個包含奇數位和偶數位的整數。

  • 宣告兩個變數,一個用於計數奇數位,另一個用於計數偶數位,並將它們初始化為0。

  • 開始迴圈,當數字大於0時,用“digit/10”遞減它,這樣我們就可以獲取整數中的個位數字。

  • 如果數字能被2整除,則為偶數,否則為奇數。

  • 如果找到的數字是偶數,則偶數計數加1;如果找到的數字是奇數,則奇數計數加1。

  • 現在,為了檢查偶數位是否出現偶數次,將偶數計數除以2,如果結果為0,則它出現偶數次,否則出現奇數次。

  • 為了檢查奇數位是否出現奇數次,將奇數計數除以2,如果結果不為0,則它出現奇數次,否則出現偶數次。

  • 列印結果。

示例

 線上演示

#include <iostream>
using namespace std;
int main(){
   int n = 12345, e_count = 0, o_count = 0;
   int flag;
   while (n > 0){
      int rem = n % 10;
      if (rem % 2 == 0){
         e_count++;
      } else {
         o_count++;
      }
      n = n / 10;
   }
   cout << "Count of Even numbers : "<< e_count;
   cout << "\nCount of Odd numbers : "<< o_count;
   // To check the count of even numbers is even and the
   // count of odd numbers is odd
   if (e_count % 2 == 0 && o_count % 2 != 0){
      flag = 1;
   } else {
      flag = 0;
   }
   if (flag == 1){
      cout << "\nYes " << endl;
   } else {
      cout << "\nNo " << endl;
   }
   return 0;
}

輸出

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

Count of Even numbers : 2
Count of Odd numbers : 3
Yes

更新於:2020年5月15日

2K+ 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告