如何快速确定整数中的位数

How to quickly determine how many digits in an int?

本文关键字:整数 何快速      更新时间:2023-10-16

我知道我可以做到:

n = floor(log10(i)) + 1;

或者我可以做一个快速循环:

while(i) {
  n++;
  i/=10;
}

有没有比复杂的数学运算或循环更好的方法来实现目标?例如:如果 i = 1234,则 n = 4。

我知道的最短方法(不是计算上的,只是在键入方面(是调用snprintf(3)

int n = snprintf(NULL, 0, "%d", i);
将其

转换为字符串(itoa(并计算字符数?(虽然可能不是最好的性能(