tags:

views:

250

answers:

9

I have an integer and need to find out how many digits are in it.

+3  A: 

A little tricky to handle negative numbers and the case where the input is zero:

int length(int n)
{
   int len = 0;
   if (n < 0) { len = 1; n = -n; }
   while (n > 9) {
        n /= 10;
        len++;
   }
   return len+1;
}
socket puppet
+1 for a careful, fast approach. The spec was to count digits, so len needn't be set separately for negative values. Can init len to 1 and return len.
Tony
+8  A: 

There is no such function available in the C++ library. However you can use std::stringstream for simplicity.

Try this (Handles negative numbers as well).

   int a =-12345,x;
   x = std::abs(a)
   std::stringstream s;
   s << x;
   std::cout<<s.str().size();
Prasoon Saurav
Localisation and factoring are good: `x = a < 0 ? -a : a;`, but I'd ditch x and put that expression straight into the stream. Very C++, but very heavyweight.
Tony
+2  A: 

You have to keep dividing it by 10 (assuming it is an integer). You do this because you remove a digit each time the loop iterates.

something along the lines of:

int number;
int digits;
while (number > 0) 
{
    digits++;
    number /= 10;
}

You'll probably want to make sure the number is not zero to begin with.

aLostMonkey
+2  A: 
int intlen(float num) {
    int cnt = 0; 
    while(num >= 1) { 
        num = num / 10; 
        cnt++; 
    } 
    return cnt; 
}
Ruel
The number 0 has 0 digits in it?
dreamlax
Negative numbers have no digits either?
dreamlax
+10  A: 

For positive numbers, use log10:

int a = 1234;
int len = static_cast<int>(log10(a)+1.);

If you need to be thorough:

int length(int a)
{
  int b = abs(a);
  if (b == 0) return 1;
  return static_cast<int>(log10(b)+1.);
}

With that said, it would be a better choice to do repeated division by 10 in practice.

int length(int a)
{
  int b = 0;
  for (a = abs(a); a != 0; b++, a /= 10) continue;
  return b;
}
JoshD
Begs the question, does the Standard allow an implementation where say `log10(10)` returns 0.9999999999...? I just don't know (or trust implementations to comply as they'll do whatever their hardware does), so I prefer the digit-by-digit int approaches even though this is more mathematically elegant. Thoughts?
Tony
This underestimates by 1 - ie. for your 1234 example, it returns 3. Also, it doesn't compile (under VC++ at least) because the call to log10 is ambiguous - you need to explicitly cast the int to a double first. And I guess you meant to pass b into log10 instead of a?
Peter
You're off by one. log10(5) is 0.6989700... when you cast that back to an int, you get 0. `5` certainly has more than zero digits. Also, you take the abs(a) and put it in b, but then go ahead and take the log10 of (possibly non-positive) a anyway
TokenMacGuy
I'd have to agree with you on that. Not only are they more assuredly correct, but they may be faster, too. My idea was to answer "a single standard c++ function" that would do what he wants... and this kinda fit the bill.
JoshD
Josh, You really need to apply a ceiling function since the integer conversion truncates -- I've taken the liberty of editing your otherwise very good answer.
Mark E
@Mark: Thanks for the correction, but shouldn't it be +1 as it is now?
JoshD
@Tony: 1.0 is exactly representable as a double so I think you have a pretty good chance of it getting it right, but I don't know if it's guaranteed. Being floating point, quite possibly not. (Also: s/Begs/Raises/ ;-)
Peter
@Mark: My thought was that I would want 1.995 (that is log10(99)) to truncate to 1. (Then add one, which I missed.) So, your suggestion of ceiling would be spot on. Thank you for catching my error.
JoshD
@Peter: Yes, 1.0 is representable, but might not the floating point log10 calculation itself sum successive values from lookup tables or sub-calculations as they home in on the answer? Could this not produce an answer ever so slightly less than 1.0/2.0 etc? I can only test on Intel/AMD right now, which seem fine. And I have read about the history of begging questions, but can't get excited about it. "Which" where it should be "that" really bugs me though. ;->
Tony
@Tony: It might well, I was just thinking that there's a fair chance of that not being a problem if the argument and answer are integer - at least it doesn't appear to break for me either. I agree that it's not guaranteed, but seems like it might be one of those things that always does work - I guess it would depend how critical this code is :)
Peter
+7  A: 

You probably mean you have a string containing numbers rather than an int in python:

>>> i = 123456789
>>> len(i)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(str(i))
9

If this is also the case in c++ it's easy to find the length of a string using:

my_str_value.length()

or for a C string using strlen

Peter McGrattan
A: 

Here is a little example:

int numberDigits(int n) {
  char buffer[100];
  itoa(n,buffer,10);
  int len=0;
  while (buffer[len]!=0) { len++; }
  return len;
}
Alexander Rafferty
Worth listing as an alternative. Should skip any leading '-'. Despite avoiding strlen(), just the atoi() is sure to be slower than other div-by-10 solutions....
Tony
That would be an issue if speed is very sensitive in his application.
Alexander Rafferty
+5  A: 

Hmm... Python:

>>> len(5)

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    len(5)
TypeError: object of type 'int' has no len()

not what you wanted?

well, lets suppose you have an actual integer. the log base 10 will tell you what you want to know numerically, that is if yournumber == pow(10, digits), then log10(yournumber) == digits! unfortunately, if your number is not an exact power of 10, you will have a fraction part to deal with. That's easy enough to deal with, though, with the floor() function, which just rounds down. be wary of negative numbers, as logarithms are undefined in the real numbers for non-positive values.

#include <iostream>
#include <math.h>

int main()
{
  std::cout << floor(log10(5))+1 << std::endl;
  std::cout << floor(log10(30))+1 << std::endl;
  std::cout << floor(log10(2000))+1 << std::endl;
  std::cout << floor(log10(16000))+1 << std::endl;
}

we have to add 1 because 10 to the 1'st is still 10, so we're off by one. Add one to the exponent and you have digits!

TokenMacGuy
Excellent explanation. +1 How do you feel about the possible precision issues with floating point that were raised in my answer's comments?
JoshD
@JoshD: well, `log10(x)` is undefined for non-positive x, but aside from that issue, this will always be correct. Note that `log10(10.0)` is exactly 1.0. the floor of that is 1, 1+1 is two.
TokenMacGuy
A: 

Ignoring for the moment that len() in python returns the number of items in a sequence and not the number of digits in an integer, here's a function to count the number of digits in an integer without dividing (so it should be much faster than the similar solutions which use division).

int number_of_digits(int value)
{
    int count = 0;
    int i = 1;

    if (value < 0)
    {
        value *= -1;
    }

    while (i < value)
    {
        count++;
        i *= 10;
    }

    if (count > 0)
    {
        return count;
    }
    else
    {
        return 1;
    }
}

For extra speed, you can even replace the multiplication by ten with some bit twiddling:

i = ((i << 2) + i) << 1;

(The bit shifting is cool, but the multiplication may be "free" if your CPU can pipeline the multiplication on some otherwise unused multiplication unit - modern processors are a thing of beauty).

Seth