📌  相关文章
📜  不超过 M 后缀 N 的所有可能数字的计数

📅  最后修改于: 2021-10-26 05:44:11             🧑  作者: Mango

给定两个正整数NM ,任务是找到范围[1, M]中所有可能数字的计数,后缀为N

例子:

朴素的方法:最简单的方法是遍历[1, M]范围内的所有整数,并检查后缀是否为N。
时间复杂度: O(M)
辅助空间: O(1)

高效的方法:要优化上述方法,需要进行以下观察:

因此,为了计算 [1, M] 范围内可能的数字的计数,需要计算以下表达式:

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
 
using namespace std;
 
// Function to count the
// no. of digits of N
int digitsOf(int num)
{
    return to_string(num).size();
}
 
// Function to count all possible
// numbers having Suffix as N
int count(int a, int tn)
{
    // Difference of the A.P
    int diff = pow(10, digitsOf(a));
 
    // Count of the number of terms
    return ((tn - a) / diff) + 1;
}
 
// Driver Code
int main()
{
 
    int n, m;
    n = 25, m = 4500;
    cout << count(n, m);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to count the
// no. of digits of N
static int digitsOf(int num)
{
    return Integer.toString(num).length();
}
 
// Function to count all possible
// numbers having Suffix as N
static int count(int a, int tn)
{
     
    // Difference of the A.P
    int diff = (int)Math.pow(10, digitsOf(a));
 
    // Count of the number of terms
    return ((tn - a) / diff) + 1;
}
 
// Driver code
public static void main (String[] args)
{
    int n = 25, m = 4500;
     
    System.out.println(count(n, m));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
 
# Function to count the
# no. of digits of N
def digitsOf(num):
    return len(str(num));
 
# Function to count all possible
# numbers having Suffix as N
def count(a, tn):
 
    # Difference of the A.P
    diff = int(pow(10, digitsOf(a)));
 
    # Count of the number of terms
    return ((tn - a) / diff) + 1;
 
# Driver code
if __name__ == '__main__':
    n = 25; m = 4500;
 
    print(int(count(n, m)));
 
# This code is contributed by sapnasingh4991


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to count the
// no. of digits of N
static int digitsOf(int num)
{
    return num.ToString().Length;
}
 
// Function to count all possible
// numbers having Suffix as N
static int count(int a, int tn)
{
     
    // Difference of the A.P
    int diff = (int)Math.Pow(10, digitsOf(a));
 
    // Count of the number of terms
    return ((tn - a) / diff) + 1;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 25, m = 4500;
     
    Console.WriteLine(count(n, m));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
45

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