我在一个技能测试系统中发现了下一个编程问题:
给出一个正整数 N。考虑数字序列 [0, 1, ..., N]。这些数字的十进制表示中零的总数是多少?
N 可以非常大。因此,它以长度为 L 的非空字符串 S 的形式给出,其中包含 N 的十进制表示。S 不包含前导零。
写一个函数:
int number_of_zeros(char *S);
int number_of_zeros(const string &S);
即,给定一个字符串 S,它是某个正整数 N 的十进制表示,返回数字 [0, 1, ..., N] 的十进制表示中零的总数。如果结果超过 1,410,000,016,则该函数应返回结果除以 1,410,000,017 的余数。
例如,对于 S="100",函数应该返回 12,对于 S="219",它应该返回 42。
假使,假设:
* L is an integer within the range [1..10,000];
* string S consists only of digits (0-9);
* string S contains no leading zeros.
复杂:
* expected worst-case time complexity is O(L);
* expected worst-case space complexity is O(L) (not counting the storage required for input arguments).
我试图解决它并编写函数,但在我的解决方案中运行时间复杂度比 O(L) 更复杂,任何人都可以解决它(至少提供算法或伪代码或解释)?
好成功!