C++ - how to find the length of an integer

后端 未结 13 1389
你的背包
你的背包 2020-12-09 10:03

I\'m trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use

相关标签:
13条回答
  • 2020-12-09 10:33
    int intLength(int i) {
        int l=0;
        for(;i;i/=10) l++;
        return l==0 ? 1 : l;
    }
    

    Here's a tiny efficient one

    0 讨论(0)
  • 2020-12-09 10:34

    Best way is to find using log, it works always

    int len = ceil(log10(num))+1;
    
    0 讨论(0)
  • 2020-12-09 10:37

    Being a computer nerd and not a maths nerd I'd do:

    char buffer[64];
    int len = sprintf(buffer, "%d", theNum);
    
    0 讨论(0)
  • 2020-12-09 10:39

    Not necessarily the most efficient, but one of the shortest and most readable using C++:

    std::to_string(num).length()
    
    0 讨论(0)
  • 2020-12-09 10:39

    Would this be an efficient approach? Converting to a string and finding the length property?

    int num = 123  
    string strNum = to_string(num); // 123 becomes "123"
    int length = strNum.length(); // length = 3
    char array[3]; // or whatever you want to do with the length
    
    0 讨论(0)
  • 2020-12-09 10:39

    How about (works also for 0 and negatives):

    int digits( int x ) { 
        return ( (bool) x * (int) log10( abs( x ) ) + 1 );
    }
    
    0 讨论(0)
提交回复
热议问题