给定两个整数N和K ,任务是找到所有可能的N 位数字的计数,这些数字的每K个连续数字的总和都相等。
例子:
Input: N = 2, K=1
Output: 9
Explanation:
All two digit numbers satisfying the required conditions are {11, 22, 33, 44, 55, 66, 77, 88, 99}
Input: N = 3, K = 2
Output: 90
朴素和滑动窗口方法:对于最简单的方法和基于滑动窗口技术的方法,请参阅 N 位数字的计数,其每 K 个连续数字的总和相等。
对数法:
为了使K 个连续元素的总和始终相等,整个数字由其前K位数字控制。
- 第i位数字将等于第(ik)位数字,以满足条件,即每K个连续数字的总和相同。
Illustration:
N = 5 and K = 2
If the first two digits are 1 and 2, then the number has to be 12121 so that sum of every 2 consecutive digits is 3.
Observe that the first 2 digits i.e. the first K digits repeats itself.
因此,为了解决这个问题,现在的任务是找出等于10 K – 10 (K-1)的K 位数字的总数。因此,打印计算值作为答案。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to count the number of
// N-digit numbers such that sum of
// every K consecutive digits are equal
void count(int n, int k)
{
long count = (long)(pow(10, k) - pow(10, k - 1));
// Print the answer
cout << (count);
}
// Driver Code
int main()
{
int n = 2, k = 1;
count(n, k);
}
// This code is contributed by Ritik Bansal
Java
// Java Program to implement
// the above approach
class GFG {
// Function to count the number of
// N-digit numbers such that sum of
// every K consecutive digits are equal
public static void count(int n, int k)
{
long count
= (long)(Math.pow(10, k)
- Math.pow(10, k - 1));
// Print the answer
System.out.print(count);
}
// Driver Code
public static void main(String[] args)
{
int n = 2, k = 1;
count(n, k);
}
}
Python3
# Python3 program to implement
# the above approach
# Function to count the number of
# N-digit numbers such that sum of
# every K consecutive digits are equal
def count(n, k):
count = (pow(10, k) - pow(10, k - 1));
# Print the answer
print(count);
# Driver Code
if __name__ == '__main__':
n = 2;
k = 1;
count(n, k);
# This code is contributed by 29AjayKumar
C#
// C# Program to implement
// the above approach
using System;
class GFG{
// Function to count the number of
// N-digit numbers such that sum of
// every K consecutive digits are equal
public static void count(int n, int k)
{
long count = (long)(Math.Pow(10, k) -
Math.Pow(10, k - 1));
// Print the answer
Console.Write(count);
}
// Driver Code
public static void Main(String[] args)
{
int n = 2, k = 1;
count(n, k);
}
}
// This code is contributed by Rohit_ranjan
Javascript
9
时间复杂度: O(log K)
辅助空间: O(1)