Archived

This topic is now archived and is closed to further replies.

Nibbles

getting the length of an integer

Recommended Posts

Hi, how would I go about getting the length (number of digits) in an integer, and then say find out what the first digit is? preferably in java, but C is ok too. Thanks, Scott Email Website
"If you try and don't succeed, destroy all evidence that you tried." Edited by - wojtos on November 5, 2001 3:07:20 AM

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Convert it to a string.

then the number of letters = the length and then first letter is the first number

Share this post


Link to post
Share on other sites
  
// this is the input integer

int some_integer = 265471;

// length of the number in digits

int length = 0;

// first digit of the number

int first_digit;

do
{
first_digit = some_integer;
some_integer = some_integer / 10;
++length;
}
while (some_integer != 0);



Surely you remember maths from junior school?:

1s, 10s, 100s, 1000s, 10000s etc...

It keeps dividing by 10 until the integer becomes a fraction (i.e. less than 1). Because the number is an integer, any fraction will come out as a 0.

Small gotcha is for a negative number, the first digit will also be negative (you may actually want that - if not, do an abs(x) on it).

--
Simon O''''Connor
Creative Asylum Ltd
www.creative-asylum.com

Share this post


Link to post
Share on other sites
One simple way to find the length of an integer is to use log10().

int x = 65837;

int length = log10(x)+1;

I don''t know how efficient that is, but it is easy to understand.

Share this post


Link to post
Share on other sites
in java convert to Integer class and call toString(). get the length of the string. adjust for minus sign as necessary.

int number, numberOfDigits;
Integer tempNumber;
string tempString;

tempNumber = new Integer ( Math.abs ( number ) );
tempString = tempNumber.toString ();
numberOfDigits = tempString.length ();

First digit is first char in string, or:

tempString.chatAt (0);

Share this post


Link to post
Share on other sites