number of digits in number?

This is a discussion on number of digits in number? within the C++ Programming forums, part of the General Programming Boards category; Is there any function that calculates the number of digits in an int?...

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    24

    Question number of digits in number?

    Is there any function that calculates the number of digits in an int?
    Dmitry Kashlev

  2. #2
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    The best way i can think of doing this, is to convert the int to a string using itoa(), then use a while loop with a condition to break when the first '\0' is encountered. Therefore, the string will have to be null terminated before you use itoa, within the while loop you would have a counter incrementing until the condition becomes false. You then have the number of digits from the int.
    Be a leader and not a follower.

  3. #3
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Code:
    #include <iostream.h>
    
    int main(void)
    {
      int Num, Digit=0;
      static char *StringNum;
    
      cout << "Please enter number: ";
      cin >> Num;
    
      StringNum = new char[sizeof Num + 1]; //'\0 +1'
    
      itoa(Num, StringNum, 10);
    
      while(StringNum[Digit] != '\0')
        Digit++;
    
      delete StringNum;
      StringNum=NULL;
    
      cout << "\nThe number: " << Num << ". Contains " << Digit << " digit(s).";
      getchar();
    
      return 0;
    }
    Be a leader and not a follower.

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    66
    Peform a loop that increments a counter variable and divide the number or a copy of the number by the base until it reaches 0.
    Code:
    #include <iostream.h>
    
    int main ( )
    {
        int number = 64789, copyof;
        int count = 0;
    
        copyof = number;
        while (copyof){
            count++;
            copyof /= 10;
        }
        cout<<"There are "<<count<<" digits in "<<number<<".\n";
    
        return 0;
    }
    Last edited by Crimpy; 08-10-2002 at 06:58 PM.

  5. #5
    silentstrike
    Guest
    I got a little bored. Looks like division by 10 is the way to go.

    Code:
    #include <cmath>
    #include <ctime>
    #include <iostream>
    #include <sstream>
    #include <iomanip>
    
    using namespace std;
    
    const int test_iterations=int(1e7);
    
    int numDigitsWithDivBy10(int n) {
    	if (n == 0) return 1;
    	int count=0;
    	while (n) {
    		count++;
    		n/=10;
    	}
    	return count;
    }
    
    int numDigitsWithLog(int n) {
    	if (n < 0) n = -n;  // log of negative illegal
    	else if (n == 0) return 1; // log 0 illegal
    	return int(log10(double(n)))+1;
    }
    
    int numDigitsWithSStream(int n) {
    	if (n < 0) n = -n; // don't want to count negative sign in length of string
    	ostringstream out;
    	out << n;
    	return (int) out.str().length();
    }
    
    // test for correct results
    void test(int n) {
    	std::cout << setw(13) <<  n << '\t' << numDigitsWithLog(n) << '\t' << numDigitsWithSStream(n)
    	<< '\t' << numDigitsWithDivBy10(n) << endl;
    }
    
    int main() {
    	int i;
    
    	for (i = 1; i < INT_MAX/10; i*=10) {
    		test(i);
    		test(i - 1);
    		test(-i);
    		test(-i + 1);
    	}
    
    	time_t start=time(NULL);
    	for (i = 0; i < test_iterations; ++i) {
    		numDigitsWithLog(i);
    	}
    	cout << "numDigitsWithLog for " << test_iterations << " took " << time(NULL) - start << " seconds " <<endl;
    
    /*	start=time(NULL);
    	for (i = 0; i < test_iterations; ++i) {
    		numDigitsWithSStream(i);
    	}
    	cout << "numDigitsWithSStream for " << test_iterations << " took " << time(NULL) - start << " seconds " <<endl;
    */
    
    	start=time(NULL);
    	for (i = 0; i < test_iterations; ++i) {
    		numDigitsWithDivBy10(i);
    	}
    	cout << "numDigitsWithDivBy10 for " << test_iterations << " took " << time(NULL) - start << " seconds " <<endl;
    
    	return 0;
    }

  6. #6
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Forgot to log in, so I can't edit it . Oh well.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  7. #7
    Registered User
    Join Date
    Jun 2002
    Posts
    267
    Originally posted by silentstrike
    I got a little bored.
    This is what you do when you're bored?

  8. #8
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Yeah.. pretty enjoyable
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  9. #9
    Registered User
    Join Date
    Aug 2002
    Posts
    24
    what is sstream header in silentstrike's code?
    Dmitry Kashlev

  10. #10
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    It for NumDigitsWithSStream. It basically lets you write to a string with <<. It similair to cout (in that it is an output stream), but instead of writing to the console, it writes to it's own private buffer, which can be converted to a string with the .str() method.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  11. #11
    ps_th
    Guest
    or you can use log10().
    Here's an example

    #include <iostream>
    #include <cmath>

    using namespace std;

    int main()
    {
    int n=1078;
    cout<<n<<" has "<<static_cast<int>(log10(n))+1<<" digits\n";
    return 0;
    }

  12. #12
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    I had that in my post already.. benchmarked it, ran about 2.5 times slower than the division by 10 method.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,422
    Well if you're out for speed, try this.

    It's a bit long compared to some of the others, but it is rather quick

    Would be somewhat unpleasant to extent to 64 bits though

    Code:
    int num_len ( int n ) {
        if (n < 0) n = -n;
        if ( n <= 99999 ) {
            if ( n <= 999 ) {
                if ( n <= 9 )  return 1;
                if ( n <= 99 ) return 2;
                return 3;
            } else {
                if ( n <= 9999 ) return 4;
                else             return 5;
            }
        } else {
            if ( n <= 9999999 ) {
                if ( n <= 999999 ) return 6;
                else               return 7;
            } else {
                if ( n <= 99999999 ) return 8;
                else                 return 9;
            }
        }
    }
    The stats for 1e8 iterations (too quick to measure at 1e7)
    numDigitsWithLog for 100000000 took 67 seconds
    numDigitsWithDivBy10 for 100000000 took 31 seconds
    num_len for 100000000 took 3 seconds

  14. #14
    Nick
    Guest
    What about this one
    Code:
    int num_digits(int n)
    {
        int count = 0;
    
        if (n < 10)
            return 1;
        else if (n < 100)
            return 2;
    
        do {
            count += 3;
            n /= 1000;
        } while(n >= 1000);
    
        if (n) {
            count++;
            if (n >= 10) {
                count++;
                if (n >= 100)
                    count++;
            }
        }
    
        return count;
    }

  15. #15
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Still somewhat slower. You can cut out the top if statements
    and make the do while into a while.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf oddities
    By robwhit in forum C Programming
    Replies: 5
    Last Post: 09-22-2007, 01:03 AM
  2. Learning Memory, Ins and Outs?
    By Zoiked in forum C Programming
    Replies: 1
    Last Post: 08-27-2007, 04:43 PM
  3. numeric header - number of digits
    By Mario F. in forum C++ Programming
    Replies: 4
    Last Post: 11-16-2006, 11:02 AM
  4. Count the number of vowels, consonants, digits etc.
    By kumar14878 in forum C Programming
    Replies: 3
    Last Post: 05-09-2005, 12:34 AM
  5. Extracting individual digits from a short
    By G'n'R in forum C Programming
    Replies: 9
    Last Post: 08-30-2001, 10:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21