用C++統計包含奇數個0的N位數
給定一個數字N作為輸入。目標是找到所有N位數,這些數字的0的個數為奇數。數字也可能包含前導零,例如,如果N=3,則包含的數字將是000、011、012……990。
讓我們透過例子來理解。
輸入 − N=3
輸出 − 包含偶數個0的N位數的個數為 − 244
解釋 − 所有3位數將類似於−
Smallest will be 000, then 011,012,013,0014…..Highest will be 990.
輸入 − N=5
輸出 − 包含偶數個0的N位數的個數為 − 33616
解釋 − 所有5位數將類似於−
Smallest will be 00000, then 00011,00012,00013,0014…..Highest will be 99990.
下面程式中使用的方法如下
我們首先計算總的N位數T=10N-1。然後計算所有N位數中0的個數為偶數的數字,即E=10N-8N。剩餘的數字中0的個數為奇數的將為(T-E)/2。
輸入一個整數N。
函式count_dd(int N)接收N並返回包含奇數個0的N位數的個數。
總的N位數為total=pow(10,N)-1
數字中0的個數為偶數的總N位數為even=pow(10,N)-pow(8,N)。
數字中0的個數為奇數的剩餘個數為odd=(total-even)/2。
返回odd作為包含奇數個0的N位數的個數。
示例
#include <bits/stdc++.h> using namespace std; int count_odd(int N){ int total = pow(10, N); int even = pow(8, N); int odd = (total - even) / 2; return odd; } int main(){ int N = 4; cout<<"Count of Numbers with N digits which consists of odd number of 0's are: "<<count_odd(N); return 0; }
輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count of Numbers with N digits which consists of odd number of 0's are: 2952
廣告