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
getting the length of an integer
Convert it to a string.
then the number of letters = the length and then first letter is the first number
then the number of letters = the length and then first letter is the first number
// this is the input integerint some_integer = 265471;// length of the number in digitsint length = 0;// first digit of the numberint 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
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.
int x = 65837;
int length = log10(x)+1;
I don''t know how efficient that is, but it is easy to understand.
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);
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);
i don''t think java has the log10 function...
try base converting
numdigs = Math.log(num) / Math.log(10) + 1;
then
firstdig = (int)(num/(Math.pow(10,numdigs-1)));
try base converting
numdigs = Math.log(num) / Math.log(10) + 1;
then
firstdig = (int)(num/(Math.pow(10,numdigs-1)));
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement