Question

I wrote this function to count and return the number of digits, or the length, of the number passed to the function. It works great until you tell it to count the digits in a number with more than 10 digits. In those cases it simply returns 1.

int digits(int z)
{
  int counter = 1;
  for ( double y = 9; z > y; y = (y*10) + 9)
  {
    counter++;
  }
return counter;
}
Was it helpful?

Solution

An integer is most likely 32 bits on your target machine. If signed, an integer holds a value between (roughly) -2 billion and +2 billion. Either extreme is 10 digits long.

You could change your code to work with 64-bit integers for a bit more mileage. Otherwise you'll need to use a custom representation (ie, write your own large integer class) to allow for arbitrarily large numbers.

OTHER TIPS

Range of 4 byte int is from –2,147,483,648 to 2,147,483,647

If you specify any positive number less than 2,147,483,647 then it will count it else it will return 1.

I think you should check the range. as for int it is -2,147,483,648 to 2,147,483,647 Any number less than lower limit i.e -2,147,483,648 or anything greater than Higher limit i.e 2,147,483,647 will produce 1 as result. That you have specified in the question. click here for details.

You have issues in your code:

  1. Not considering negative values
  2. Using floating point

To address 1.: You need an absolute value: int u = std::abs(z).

Attention: The absolute value of the most negative integer is not defined.

To address 2.: Increment the counter and decrement u if 10 <= u. After that you can use your loop with an int y and u.

In addition: Most likely the test you are performing is passing a negative number, due to an overflow in a multiplication by 10.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top