简体   繁体   中英

Ways to Detect Digits Not Zero in an int?

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!

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');
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM