📜  用N位数字计数数字,该数字由0的奇数组成

📅  最后修改于: 2021-04-26 10:17:27             🧑  作者: Mango

给我们一个数字N。任务是找到具有N个数字和零的奇数的数字的计数。
注意:数字可以以0开头。

例子

Input : N = 2
Output : Count = 18

Input : N = 3
Output : Count = 244

假设一个N位数字仅包含一个零。因此,只能以1种方式填充数字中的数字为零,其余位置可以用9种不同的方式填充从1到9的数字。因此,用N位数字对所有此类数字进行计数,并且只有1个零= N C 1 *(9 N-1 )
类似地,所有具有N位数字和3个零的数字的计数= N C 3 *(9 N-3 )
等等。
因此,所有具有N位数字和奇数个零的数字的计数将为,

上面的等式可以写成:

上式可以表示为两个序列的减法,(9 N )* {((1 + x) N- (1-x) N } / 2,其中x = 1/9
等于

(10N - 8N)/2

下面是上述方法的实现:

C++
// C++ program to count numbers with N digits
// which consists of odd number of 0's
#include 
using namespace std;
 
// Function to count Numbers with N digits
// which consists of odd number of 0's
int countNumbers(int N)
{
    return (pow(10, N) - pow(8, N)) / 2;
}
 
// Driver code
int main()
{
    int n = 5;
 
    cout << countNumbers(n) << endl;
 
    return 0;
}


Java
// Java program to count numbers
// with N digits which consists
// of odd number of 0's
import java.io.*;
 
class GFG {
 
    // Function to count Numbers
    // with N digits which consists
    // of odd number of 0's
    static int countNumbers(int N)
    {
        return (int)(Math.pow(10, N)
                     - Math.pow(8, N)) / 2;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 5;
        System.out.println(countNumbers(n));
    }
}
 
// This code is contributed by Shashank


Python 3
# Python 3 program to count numbers
# with N digits which consists of
# odd number of 0's
 
# Function to count Numbers with
# N digits which consists of odd
# number of 0's
 
 
def countNumbers(N):
 
    return (pow(10, N) - pow(8, N)) // 2
 
 
# Driver code
if __name__ == "__main__":
 
    n = 5
 
    print(countNumbers(n))
 
# This code is contributed
# by ChitraNayal


C#
// C# program to count numbers
// with N digits which consists
// of odd number of 0's
using System;
 
class GFG {
 
    // Function to count Numbers
    // with N digits which consists
    // of odd number of 0's
    static int countNumbers(int N)
    {
        return (int)(Math.Pow(10, N)
                     - Math.Pow(8, N)) / 2;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 5;
        Console.WriteLine(countNumbers(n));
    }
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP


Javascript


输出
33616

注意:答案可能非常大,因此对于大于9的N,请使用模幂。

时间复杂度: O(log n)
辅助空间: O(1)

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”