【发布时间】:2020-11-28 11:08:53
【问题描述】:
我们必须找到生成给定数字所需的最小位数,例如:14 => 95 (9 + 5 = 14) 是两位数,这是形成 14 的最小值。
int moves(int n) {
int m = 0; // Minimum count
while (n-9 >= 0) { // To place maximum number of 9's
n -= 9;
m++;
}
if (n == 0) { // If only nines made up the number
return m;
}
else {
m++;
return m;
}
}
我收到了一位在线法官的 TLE(超出运行时间限制)。我该如何改进它或有更好的方法?
【问题讨论】:
-
它似乎工作正常。即使将
2^31-1分配给n,使用g++ -std=c++14 -O2仍不超过0.1 秒。 -
不需要循环。查找 mod 运算符。
-
这能回答你的问题吗? Finding the number of digits of an integer
-
在 O(1) 中与您的结果相同的函数体:
return n/9 + (n % 9 == 0 ? 0 : 1); -
你需要
a = floor(n/9)9,和数字n-9a