找到的整数的位数 [英] Finding the number of digits of an integer

查看:165
本文介绍了找到的整数的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是找到的正整数的位数的最佳方法?

What is the best method to find the number of digits of a positive integer?

我发现这3种基本方式:

I have found this 3 basic methods:

  • 转换为字符串

  • conversion to string

String s = new Integer(t).toString(); 
int len = s.length();

  • 循环

  • for loop

    for(long long int temp = number; temp >= 1;)
    {
        temp/=10;
        decimalPlaces++;
    } 
    

  • logaritmic计算

  • logaritmic calculation

    digits = floor( log10( number ) ) + 1;
    

  • 在这里,你可以计算出在大多数语言LOG10(X)= LN(X)/ LN(10)。

    where you can calculate log10(x) = ln(x) / ln(10) in most languages.

    首先,我认为该字符串的方法是最脏的一个,但我越去想它,我就越觉得这是最快的方法。或者是什么?

    First I thought the string method is the dirtiest one but the more I think about it the more I think it's the fastest way. Or is it?

    推荐答案

    总是有这种方式:

    n = 1;
    if (i >= 100000000){i /= 100000000; n += 8;}
    if (i >= 10000){i /= 10000; n += 4;}
    if (i >= 100){i /= 100; n += 2;}
    if (i >= 10){i /= 10; n += 1;}
    

    这篇关于找到的整数的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆