在C ++中对N位数字进行计数,该数字由0的奇数组成

给定数字N作为输入。目标是找到所有奇数均为0的N个数字。该数字也可以具有前面的零,例如在N = 3的情况下,该数字将为000,011,012….990。

让我们通过示例来理解。

输入-N = 3

输出-计数 N位数字由偶数个0组成的是-244

说明-所有3位数字将类似于-

Smallest will be 000, then 011,012,013,0014…..Highest will be 990.

输入-N = 5

输出-计数 N个数字由偶数个0组成的是-33616

说明-所有5位数字将类似于-

Smallest will be 00000, then 00011,00012,00013,0014…..Highest will be 99990.

以下程序中使用的方法如下

我们将首先计算N个数字总数T = 10N-1。然后计算所有N个数字,偶数为0,即E = 10N-8N。剩余的奇数位数为(TE)/ 2。

  • 以整数N作为输入。

  • 函数count_dd(int N)取N,并返回带有奇数0的N个数字的计数。

  • N个数字总数为total = pow(10,N)-1

  • N个数字中偶数为0的总数为even = pow(10,N)-pow(8,N)。

  • 剩余的奇数0位数为奇数=(总数-2)/ 2。

  • 返回奇数作为N个数字的计数,奇数为0。

示例

#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
猜你喜欢