给定三个整数A,L和R ,任务是计算范围为L到R的数字,该数字包含A作为其后缀。
例子:
Input: A = 2, L = 2, R = 20
Output: 2
Explanation:
Only two possible numbers from the given range that satisfies the conditions are 2 and 12.
Input: A = 25, L = 25, R = 273
Output: 3
Explanation:
The three numbers from the given range that satisfies the conditions are 25, 125 and 225.
天真的方法:解决问题的最简单方法是遍历范围L到R的数字,并检查数字是否以A结尾。对于所有发现为真的数字,将这些数字的计数加1。最后,打印最终计数。
时间复杂度: O(B)
辅助空间: O(log 2 R)
高效方法:要优化上述方法,请按照以下步骤操作:
- 计算并存储A的位数,并将其存储在变量中,例如count。
- 将A的位数提高10,即10 count 。
- 检查每个10计数周期是否在[L,R]范围内。如果发现为真,则将计数增加1。
- 打印count的最终值。
下面是上述方法的实现:
C++
// C++ Program of the
// above approach
#include
using namespace std;
// Function to count the number
// ends with given number in range
void countNumEnds(int A, int L, int R)
{
int temp, count = 0, digits;
int cycle;
// Find number of digits in A
digits = log10(A) + 1;
// Find the power of 10
temp = pow(10, digits);
cycle = temp;
while (temp <= R) {
if (temp >= L)
count++;
// Incrementing the A
temp += cycle;
}
cout << count;
}
// Driver Code
int main()
{
int A = 2, L = 2, R = 20;
// Function Call
countNumEnds(A, L, R);
}
Java
// Java Program of the
// above approach
class GFG{
// Function to count the number
// ends with given number in range
static void countNumEnds(int A,
int L, int R)
{
int temp, count = 0, digits;
int cycle;
// Find number of digits in A
digits = (int) (Math.log10(A) + 1);
// Find the power of 10
temp = (int) Math.pow(10, digits);
cycle = temp;
while (temp <= R)
{
if (temp >= L)
count++;
// Incrementing the A
temp += cycle;
}
System.out.print(count);
}
// Driver Code
public static void main(String[] args)
{
int A = 2, L = 2, R = 20;
// Function Call
countNumEnds(A, L, R);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program of the
# above approach
from math import log10
# Function to count the number
# ends with given number in range
def countNumEnds(A, L, R):
count = 0
# Find number of digits in A
digits = int(log10(A) + 1)
# Find the power of 10
temp = int(pow(10, digits))
cycle = temp
while(temp <= R):
if(temp >= L):
count += 1
# Incrementing the A
temp += cycle
print(count)
# Driver Code
A = 2
L = 2
R = 20
# Function call
countNumEnds(A, L, R)
# This code is contributed by Shivam Singh
C#
// C# program of the
// above approach
using System;
class GFG{
// Function to count the number
// ends with given number in range
static void countNumEnds(int A, int L,
int R)
{
int temp, count = 0, digits;
int cycle;
// Find number of digits in A
digits = (int)(Math.Log10(A) + 1);
// Find the power of 10
temp = (int)Math.Pow(10, digits);
cycle = temp;
while (temp <= R)
{
if (temp >= L)
count++;
// Incrementing the A
temp += cycle;
}
Console.Write(count);
}
// Driver Code
public static void Main(String[] args)
{
int A = 2, L = 2, R = 20;
// Function call
countNumEnds(A, L, R);
}
}
// This code is contributed by Amit Katiyar
Javascript
输出:
2
时间复杂度: O(N),其中N是范围。
辅助空间: O(1)