如何找出c ++中数字的位数?

sar*_*ara 3 c++

我想知道c ++中数字的位数,但我不知道我该怎么办?例如,位数7676575.

Ker*_* SB 11

取数字的基数 - 对数10的上限.(或者更一般地"碱基Ñ "为在碱数字位数Ñ.)

在代码中:std::ceil(std::log10(n + 1)),并确保#include <cmath>.

(作为特殊情况,您将获得0输入答案0.由您决定如何处理负数.)

@Knaģis的答案中的代码可能更有效,因为常量10的除法可以由编译器转换为乘法并且相当便宜.如果这对性能至关重要,则必须进行分析和比较,如果这仅适用于整数类型.对数方法还允许您计算非常大的浮点数的假设十进制扩展中的位数.

  • 嗯,你用什么算法?大数字可以很容易地使用位移(参见维基百科),我不明白为什么你需要十进制数字. (2认同)

Kna*_*ģis 7

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)