C++ 吧里看到有人求助, 说是想写点代码求一个整数的位数, 以下是我的解决方法:
int64_t RecursionIter (const int64_t& num,
const int64_t& result)
{
if (num / 10 == 0) {
return result;
}
else {
return RecursionIter (num / 10, (result + 1));
}
}
int64_t Recursion (const int64_t& num)
{
return RecursionIter (num, 1);
}
而参考下一篇博客的思路, 也很容易写出解法的迭代版本:
int32_t Fuck (int64_t num)
{
int32_t result = 1;
while (num / 10 != 0) {
num /= 10;
++result;
}
return result;
}
迭代的话, 这样似乎更快:
int32_t Fuck (int64_t num)
{
if (num < 0) {
num *= -1;
}
int32_t result = 1;
while (num >= 10) {
num /= 10;
++result;
}
return result;
}