Ker*_* SB 11
取数字的基数 - 对数10的上限.(或者更一般地"碱基Ñ "为在碱数字位数Ñ.)
在代码中:std::ceil(std::log10(n + 1))
,并确保#include <cmath>
.
(作为特殊情况,您将获得0
输入答案0
.由您决定如何处理负数.)
@Knaģis的答案中的代码可能更有效,因为常量10的除法可以由编译器转换为乘法并且相当便宜.如果这对性能至关重要,则必须进行分析和比较,如果这仅适用于整数类型.对数方法还允许您计算非常大的浮点数的假设十进制扩展中的位数.
int i = 7676575;
int digits = i == 0 ? 1 : 0;
i = abs(i); // handle negative numbers as well
while (i > 0)
{
digits++;
i /= 10;
}
// -or- if you prefer do/while then a shorter sample (by Kerrek SB)
int i = 7676575;
int digits = 0;
i = abs(i); // handle negative numbers as well
do { digits++; } while (i /= 10);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
587 次 |
最近记录: |