program tip

숫자의 총 자릿수를 어떻게 구할 수 있습니까?

radiobox 2020. 8. 26. 07:45
반응형

숫자의 총 자릿수를 어떻게 구할 수 있습니까?


C #에서 숫자의 총 자릿수를 구하려면 어떻게해야합니까? 예를 들어, 숫자 887979789는 9 자리 숫자입니다.


문자열로 변환하지 않고 시도해 볼 수 있습니다.

Math.Ceiling(Math.Log10(n));

ysap의 의견에 따른 수정 :

Math.Floor(Math.Log10(n) + 1);

이 시도:

myint.ToString().Length

작동합니까?


다음 확장 중 하나가 작업을 수행합니다.

public static class Int32Extensions
{
    // THE MATHEMATICALLY FORMULATED ONE:
    public static int Digits1(this Int32 n) =>
        n == 0 ? 1 : 1 + (int) Math.Log10(Math.Abs(n));

    // TYPICAL PROGRAMMING APPROACH:
    public static int Digits2(this Int32 n)
    {
        int digits = 0;
        do { ++digits; n /= 10; } while (n != 0);
        return digits;
    }

    // THE UGLIEST POSSIBLE THING:
    public static int Digits3(this Int32 n)
    {
        n = Math.Abs(n);
        if (n < 10) return 1;
        if (n < 100) return 2;
        if (n < 1000) return 3;
        if (n < 10000) return 4;
        if (n < 100000) return 5;
        if (n < 1000000) return 6;
        if (n < 10000000) return 7;
        if (n < 100000000) return 8;
        if (n < 1000000000) return 9;
        return 10;
    }

    // THE LOCOMOTIVE PULLING CHARACTERS:
    public static int Digits4(this Int32 n) =>
        n >= 0 ? n.ToString().Length : n.ToString().Length - 1;
}

나는 5 개의 다른 시나리오에서 for 루프에서 100.000.000 호출, Stopwatch.

그리고 승자는 ...

-1000000000.Digits1()  =>   1806 ms
-1000000000.Digits2()  =>   4114 ms
-1000000000.Digits3()  =>    664 ms <<<
-1000000000.Digits4()  =>  13600 ms

-1000.Digits1()  =>  1839 ms
-1000.Digits2()  =>  1163 ms
-1000.Digits3()  =>   429 ms <<<
-1000.Digits4()  =>  9959 ms

0.Digits1()  =>   166 ms <<<
0.Digits2()  =>   369 ms
0.Digits3()  =>   165 ms <<<
0.Digits4()  =>  7416 ms

1000.Digits1()  =>  1578 ms
1000.Digits2()  =>  1182 ms
1000.Digits3()  =>   328 ms <<<
1000.Digits4()  =>  9296 ms

1000000000.Digits1()  =>   1596 ms
1000000000.Digits2()  =>   4074 ms
1000000000.Digits3()  =>    581 ms <<<
1000000000.Digits4()  =>  13679 ms

가장 추악한 일!


직접 C #은 아니지만 공식은 다음과 같습니다. n = floor(log10(x)+1)


이미 여기에있는 답변은 부호없는 정수에 대해 작동하지만 소수와 두 배에서 자릿수를 얻는 좋은 솔루션을 찾지 못했습니다.

public static int Length(double number)
{
    number = Math.Abs(number);
    int length = 1;
    while ((number /= 10) >= 1)
        length++;
    return length;
}
//number of digits in 0 = 1,
//number of digits in 22.1 = 2,
//number of digits in -23 = 2

정밀도가 중요한 경우 입력 유형을에서 double변경할 수 decimal있지만 십진수도 제한이 있습니다.


재귀 사용 (간혹 인터뷰에서 요청 됨)

public int CountDigits(int number)
{
    // In case of negative numbers
    number = Math.Abs(number);

    if (number >= 10)
        return CountDigits(number / 10) + 1;
    return 1;
 }

The answer of Steve is correct, but it doesn't work for integers less than 1.

Here an updated version that does work for negatives:

int digits = n == 0 ? 1 : Math.Floor(Math.Log10(Math.Abs(n)) + 1)

static void Main(string[] args)
{
    long blah = 20948230498204;
    Console.WriteLine(blah.ToString().Length);
}

dividing a number by 10 will give you the left most digit then doing a mod 10 on the number gives the number without the first digit and repeat that till you have all the digits


int i = 855865264;
int NumLen = i.ToString().Length;

It depends what exactly you want to do with digiths. You can iterate by number digits starting from the last one to first one this way:

int tmp=number;
int lastDigith = 0;
do
{
    lastDigith = tmp/10;
    doSomethingWithDigith(lastDigith);
    tmp %= 10;
}while(tmp!=0);

convert into string and then you can count tatal no of digit by .length method. Like:

String numberString = "855865264".toString();
int NumLen = numberString .Length;

If its only for validating you could do: 887979789 > 99999999


Assuming your question was referring to an int, the following works for negative/positive and zero as well:

Math.Floor((decimal) Math.Abs(n)).ToString().Length

참고URL : https://stackoverflow.com/questions/4483886/how-can-i-get-a-count-of-the-total-number-of-digits-in-a-number

반응형