给定一个正整数N ,任务是找到整数X的数量,以便在执行以下操作序列后将N的值减少到0 。
- 从m N 中减去 X的值。
- 如果X是个位数的整数,然后停止施加动作。
- 将 X的值更新为X 的数字总和。
例子:
Input: N = 9940
Output: 1
Explanation:
Considering the value of X as 9910, the value of N can be reduced to 0 as:
- Operation 1: Update N as N – X, N = 9939 – 9910 = 30, Update X as sum of digit of X, X = 9 + 9 + 1 + 0 = 19.
- Operation 2: Update N as N – X, N = 30 – 19 = 11, Update X as sum of digit of X, X = 9 + 1 = 10.
- Operation 3: Update N as N – X, N = 11 – 10 = 1, Update X as sum of digit of X, X = 1 + 0 = 1.
- Operation 4: Update N as N – X, N = 1 – 1 = 0, Stop applying operations.
Therefore, there exists only one value of X as 1.
Input: N = 9939
Output: 3
方法:可以使用基于以下观察的贪心方法来解决给定的问题:
- 可以观察到,选择大于N的 X值不会将N减少到0 。
- 可以肯定地说,如果N 中的位数是K ,那么 X 的任何值都不会小于(N – 10 * K * (K + 1) / 2)并且可以将N转换为0 。
从上面的观察来看,想法是在范围[N – 10 * K * (K + 1) / 2, N]上进行迭代,并计算该范围内在执行给定操作后可以将 N转换为0 的那些值。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to check if the value of X
# reduces N to 0 or not
def check(x, N):
while True:
# Update the value of N as N-x
N -= x
# Check if x is a single digit integer
if len(str(x)) == 1:
break
# Update x as sum digit of x
x = sum(list(map(int, str(x))))
if len(str(x)) == 1 and N == 0:
return 1
return 0
# Fuction to find the number of values
# X such that N can be reduced to 0
# after performing the given operations
def countNoOfsuchX(N):
# Number of digits in N
k = len(str(N))
# Stores the count of value of X
count = 0
# Iterate over all possible value
# of X
for x in range(N - k*(k + 1)*5, N + 1):
# Check if x follow the conditions
if check(x, N):
count += 1
# Return the total count
return count
# Driver Code
N = 9939
print(countNoOfsuchX(N))
输出:
3
时间复杂度: O(log N)
辅助空间: O(log N)