Reputation: 574
I was curious as to if there were any simple ways to detect the number of non-zero digits in an int
/long
. I want to create a small program that formats input(standard numbers) to scientific notation.
I've tried to find any int
functions that could help do this, but I'm not 100% fluent and there weren't any that seemed like they would help.
Also, I want to find a way to put each digit from an int
/long
into a list with each digit being it's own element. Maybe there is a way from there to separate zero's from non-zero's.
Any fancy ideas (and comments) will be appreciated, thanks!
Upvotes: 1
Views: 948
Reputation: 8099
Count the number of non zero digits in a number
int NumOfNonZeroDigits(long num)
{
int result = 0;
while( num != 0)
{
if(num % 10 != 0)
{
result++;
}
num /= 10;
}
return result;
}
print indevidual digits:
int num = 43546;
int digitNum = (int) Math.Floor(Math.Log10(n) + 1);
for (int i=0; i <digitNum; i++)
{
int digit = (num / ((int) Math.Pow(10, i)) ) % 10;
Console.Writeline(digit);
}
// the third dight would be: (num / 100) % 10
Upvotes: 2
Reputation: 5017
First of all, zeroes? What is a zero in a binary representation of an integer? When you turn it into a decimal value and print it to screen?
And if all you want is scientific notation, I would recommend having a look at the MSDN-documentation for scientific notation.
Example:
var t = 1234.5678d;
Console.WriteLine(t.ToString("E", CultureInfo.InvariantCulture));
// Will print something along the lines of 1.2345678E+004
Upvotes: 1
Reputation: 116558
You could simply turn it into a string (using InvariantCulture
) and count only the non zero digits:
public int NonZeroDigits(int input)
{
return input.ToString(CultureInfo.InvariantCulture).Count(digit => digit >= '1' && digit <= '9');
}
Upvotes: 2