Sposób na uzyskanie liczby cyfr w int?

Czy istnieje lepszy sposób na uzyskanie długości Int w taki sposób?

int length = String.valueOf(1000).length();
 314
Author: John Saunders, 2009-08-20

27 answers

Twoje rozwiązanie oparte na ciągach jest idealnie OK, nie ma w tym nic "nie-schludnego". Musisz zdać sobie sprawę, że matematycznie liczby nie mają długości, ani nie mają cyfr. Długość i cyfry są zarówno właściwościami fizycznej reprezentacji liczby w określonej bazie, tj. ciągu.

Rozwiązanie oparte na logarytmie robi (niektóre) te same rzeczy, co wewnętrzne, i prawdopodobnie robi to (nieznacznie) szybciej, ponieważ produkuje tylko długość i ignoruje cyfry. Ale nie uważałbym tego za jaśniejsze w intencjach - i to jest najważniejszy czynnik.

 294
Author: Michael Borgwardt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-20 15:04:21

Logarytm jest twoim przyjacielem:

int n = 1000;
int length = (int)(Math.log10(n)+1);

Uwaga: obowiązuje tylko dla n > 0.

 232
Author: Dmitry Brant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-22 20:40:08

Najszybsze podejście: dziel i rządź.

Zakładając, że twój zakres wynosi od 0 do MAX_INT, to masz od 1 do 10 cyfr. Możesz zbliżyć się do tego interwału za pomocą divide and conquer, z maksymalnie 4 porównaniami na każde wejście. Najpierw dzielisz [1..10] do [1..5] i [6..10] z jednym porównaniem, a następnie każdy interwał długości 5 dzielisz za pomocą jednego porównania na jeden interwał długości 3 i jeden interwał długości 2. Długość 2 interwał wymaga jeszcze jednego porównania (łącznie 3 porównania), długość 3 interwał można podzielić na długość 1 interwał (roztwór) i długość 2 interwał. Więc potrzebujesz 3 lub 4 porównań.

Żadnych podziałów, żadnych operacji zmiennoprzecinkowych, żadnych drogich logarytmów, tylko porównania liczb całkowitych.

Kod (długi, ale szybki):

if (n < 100000){
        // 5 or less
        if (n < 100){
            // 1 or 2
            if (n < 10)
                return 1;
            else
                return 2;
        }else{
            // 3 or 4 or 5
            if (n < 1000)
                return 3;
            else{
                // 4 or 5
                if (n < 10000)
                    return 4;
                else
                    return 5;
            }
        }
    } else {
        // 6 or more
        if (n < 10000000) {
            // 6 or 7
            if (n < 1000000)
                return 6;
            else
                return 7;
        } else {
            // 8 to 10
            if (n < 100000000)
                return 8;
            else {
                // 9 or 10
                if (n < 1000000000)
                    return 9;
                else
                    return 10;
            }
        }
    }

Benchmark (po rozgrzewce JVM) - zobacz kod poniżej, aby zobaczyć, jak benchmark został uruchomiony:

  1. metoda bazowa (z łańcuchem znaków.długość): 2145ms
  2. log10 metoda: 711ms = 3,02 razy szybciej niż wyjściowy
  3. powtórzony podział: 2797ms = 0,77 razy faster than baseline
  4. divide-and-conquer: 74ms = 28.99
    razy szybciej niż przed rozpoczęciem

Pełny kod:

public static void main(String[] args)
throws Exception
{

    // validate methods:
    for (int i = 0; i < 1000; i++)
        if (method1(i) != method2(i))
            System.out.println(i);
    for (int i = 0; i < 1000; i++)
        if (method1(i) != method3(i))
            System.out.println(i + " " + method1(i) + " " + method3(i));
    for (int i = 333; i < 2000000000; i += 1000)
        if (method1(i) != method3(i))
            System.out.println(i + " " + method1(i) + " " + method3(i));
    for (int i = 0; i < 1000; i++)
        if (method1(i) != method4(i))
            System.out.println(i + " " + method1(i) + " " + method4(i));
    for (int i = 333; i < 2000000000; i += 1000)
        if (method1(i) != method4(i))
            System.out.println(i + " " + method1(i) + " " + method4(i));

    // work-up the JVM - make sure everything will be run in hot-spot mode
    allMethod1();
    allMethod2();
    allMethod3();
    allMethod4();

    // run benchmark
    Chronometer c;

    c = new Chronometer(true);
    allMethod1();
    c.stop();
    long baseline = c.getValue();
    System.out.println(c);

    c = new Chronometer(true);
    allMethod2();
    c.stop();
    System.out.println(c + " = " + StringTools.formatDouble((double)baseline / c.getValue() , "0.00") + " times faster than baseline");

    c = new Chronometer(true);
    allMethod3();
    c.stop();
    System.out.println(c + " = " + StringTools.formatDouble((double)baseline / c.getValue() , "0.00") + " times faster than baseline");

    c = new Chronometer(true);
    allMethod4();
    c.stop();
    System.out.println(c + " = " + StringTools.formatDouble((double)baseline / c.getValue() , "0.00") + " times faster than baseline");
}


private static int method1(int n)
{
    return Integer.toString(n).length();
}
private static int method2(int n)
{
    if (n == 0)
        return 1;
    return (int)(Math.log10(n) + 1);
}
private static int method3(int n)
{
    if (n == 0)
        return 1;
    int l;
    for (l = 0 ; n > 0 ;++l)
        n /= 10;
    return l;
}
private static int method4(int n)
{
    if (n < 100000)
    {
        // 5 or less
        if (n < 100)
        {
            // 1 or 2
            if (n < 10)
                return 1;
            else
                return 2;
        }
        else
        {
            // 3 or 4 or 5
            if (n < 1000)
                return 3;
            else
            {
                // 4 or 5
                if (n < 10000)
                    return 4;
                else
                    return 5;
            }
        }
    }
    else
    {
        // 6 or more
        if (n < 10000000)
        {
            // 6 or 7
            if (n < 1000000)
                return 6;
            else
                return 7;
        }
        else
        {
            // 8 to 10
            if (n < 100000000)
                return 8;
            else
            {
                // 9 or 10
                if (n < 1000000000)
                    return 9;
                else
                    return 10;
            }
        }
    }
}


private static int allMethod1()
{
    int x = 0;
    for (int i = 0; i < 1000; i++)
        x = method1(i);
    for (int i = 1000; i < 100000; i += 10)
        x = method1(i);
    for (int i = 100000; i < 1000000; i += 100)
        x = method1(i);
    for (int i = 1000000; i < 2000000000; i += 200)
        x = method1(i);

    return x;
}
private static int allMethod2()
{
    int x = 0;
    for (int i = 0; i < 1000; i++)
        x = method2(i);
    for (int i = 1000; i < 100000; i += 10)
        x = method2(i);
    for (int i = 100000; i < 1000000; i += 100)
        x = method2(i);
    for (int i = 1000000; i < 2000000000; i += 200)
        x = method2(i);

    return x;
}
private static int allMethod3()
{
    int x = 0;
    for (int i = 0; i < 1000; i++)
        x = method3(i);
    for (int i = 1000; i < 100000; i += 10)
        x = method3(i);
    for (int i = 100000; i < 1000000; i += 100)
        x = method3(i);
    for (int i = 1000000; i < 2000000000; i += 200)
        x = method3(i);

    return x;
}
private static int allMethod4()
{
    int x = 0;
    for (int i = 0; i < 1000; i++)
        x = method4(i);
    for (int i = 1000; i < 100000; i += 10)
        x = method4(i);
    for (int i = 100000; i < 1000000; i += 100)
        x = method4(i);
    for (int i = 1000000; i < 2000000000; i += 200)
        x = method4(i);

    return x;
}

Ponownie, benchmark:

  1. metoda bazowa (z łańcuchem znaków.długość): 2145ms
  2. log10 metoda: 711ms = 3,02 razy faster than baseline
  3. powtórzony podział: 2797ms = 0,77 razy faster than baseline
  4. divide-and-conquer: 74ms = 28.99
    razy szybciej niż wyjściowy

Edit: Po napisaniu benchmark, wziąłem sneak peak do Integer.toString z Javy 6 i stwierdziłem, że używa:

final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                  99999999, 999999999, Integer.MAX_VALUE };

// Requires positive x
static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}

Porównałem to z moim rozwiązaniem dzielenia i zwyciężania:

  1. divide-and-conquer: 104ms
  2. Java 6 solution-iteracja i porównanie: 406ms
Mój jest 4x szybszy.
 143
Author: Marian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-18 00:40:29

Dwa komentarze do twojego benchmarka: Java jest złożonym środowiskiem, co z kompilacją just-in-time i garbage collection I tak dalej, więc aby uzyskać uczciwe porównanie, ilekroć uruchamiam benchmark, zawsze: (a) załączam dwa testy do pętli, która uruchamia je w sekwencji 5 lub 10 razy. Dość często runtime na drugim przejściu przez pętlę jest zupełnie inny od pierwszego. I (b) po każdym "podejściu" robię System.gc (), aby spróbować uruchomić funkcję garbage collection. W przeciwnym razie pierwszy podejście może generować kilka obiektów, ale nie wystarczająco, aby wymusić zbieranie śmieci, wtedy drugie podejście tworzy kilka obiektów, sterta jest wyczerpana i garbage collection działa. Następnie drugie podejście jest "obciążane" za zbieranie śmieci pozostawionych przez pierwsze podejście. Bardzo niesprawiedliwe!

To powiedziawszy, żadne z powyższych nie zrobiło znaczącej różnicy w tym przykładzie.

Z tymi modyfikacjami lub bez nich, mam zupełnie inne wyniki niż ty. Kiedy biegłem to, tak, podejście toString dało czasy uruchomienia 6400 do 6600 Milis, podczas gdy podejście log topok 20,000 do 20,400 Milis. Zamiast być nieco szybszym, podejście log było dla mnie 3 razy wolniejsze.

Zauważ, że te dwa podejścia wiążą się z bardzo różnymi kosztami, więc nie jest to całkowicie szokujące: podejście toString stworzy wiele tymczasowych obiektów, które muszą zostać oczyszczone, podczas gdy podejście log wymaga bardziej intensywnych obliczeń. Więc może różnica polega na tym, że na maszynie przy mniejszej ilości pamięci, toString wymaga więcej rund zbierania śmieci, podczas gdy na maszynie z wolniejszym procesorem dodatkowe obliczenia dziennika byłyby bardziej bolesne.

Próbowałem też trzeciego podejścia. Napisałem taką małą funkcję:
static int numlength(int n)
{
    if (n == 0) return 1;
    int l;
    n=Math.abs(n);
    for (l=0;n>0;++l)
        n/=10;
    return l;           
}
To trwało od 1600 do 1900 Milis ... mniej niż 1/3 podejścia toString i 1/10 podejścia log na mojej maszynie.

Jeśli masz szeroki zakres liczb, możesz przyspieszyć go dalej, zaczynając od dzielenia przez 1,000 lub 1,000,000 do zmniejsz liczbę razy przez pętlę. Nie bawiłem się tym.

 10
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 17:25:24

Ponieważ liczba cyfr w bazie 10 liczby całkowitej wynosi po prostu 1 + truncate(log10 (Liczba)) , możesz zrobić:

public class Test {

    public static void main(String[] args) {

        final int number = 1234;
        final int digits = 1 + (int)Math.floor(Math.log10(number));

        System.out.println(digits);
    }
}

Edited ponieważ moja ostatnia edycja poprawiła przykład kodu, ale nie Opis.

 8
Author: Dirk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-20 15:03:30

Rozwiązanie Mariana dostosowane do długich liczb typu (do 9,223,372,036,854,775,807), w przypadku, gdy ktoś chce go skopiować i wkleić. W programie napisałem to dla liczb do 10000 były znacznie bardziej prawdopodobne, więc zrobiłem dla nich specyficzną gałąź. W każdym razie to nie zrobi znaczącej różnicy.

public static int numberOfDigits (long n) {     
    // Guessing 4 digit numbers will be more probable.
    // They are set in the first branch.
    if (n < 10000L) { // from 1 to 4
        if (n < 100L) { // 1 or 2
            if (n < 10L) {
                return 1;
            } else {
                return 2;
            }
        } else { // 3 or 4
            if (n < 1000L) {
                return 3;
            } else {
                return 4;
            }
        }           
    } else  { // from 5 a 20 (albeit longs can't have more than 18 or 19)
        if (n < 1000000000000L) { // from 5 to 12
            if (n < 100000000L) { // from 5 to 8
                if (n < 1000000L) { // 5 or 6
                    if (n < 100000L) {
                        return 5;
                    } else {
                        return 6;
                    }
                } else { // 7 u 8
                    if (n < 10000000L) {
                        return 7;
                    } else {
                        return 8;
                    }
                }
            } else { // from 9 to 12
                if (n < 10000000000L) { // 9 or 10
                    if (n < 1000000000L) {
                        return 9;
                    } else {
                        return 10;
                    }
                } else { // 11 or 12
                    if (n < 100000000000L) {
                        return 11;
                    } else {
                        return 12;
                    }
                }
            }
        } else { // from 13 to ... (18 or 20)
            if (n < 10000000000000000L) { // from 13 to 16
                if (n < 100000000000000L) { // 13 or 14
                    if (n < 10000000000000L) { 
                        return 13;
                    } else {
                        return 14;
                    }
                } else { // 15 or 16
                    if (n < 1000000000000000L) {
                        return 15;
                    } else {
                        return 16;
                    }
                }
            } else { // from 17 to ...¿20?
                if (n < 1000000000000000000L) { // 17 or 18
                    if (n < 100000000000000000L) {
                        return 17;
                    } else {
                        return 18;
                    }
                } else { // 19? Can it be?
                    // 10000000000000000000L is'nt a valid long.
                    return 19;
                }
            }
        }
    }
}
 5
Author: J.A.I.L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-01 09:14:01

Using Java

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

Użyj import java.lang.Math.*; na początku

Korzystanie Z C

int nDigits = floor(log10(abs(the_integer))) + 1;

Użyj inclue math.h na początku

 5
Author: Santosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-29 18:35:48

Mogę spróbować? ;)

Na podstawie rozwiązania Dirka

final int digits = number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));
 3
Author: DmitryK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-20 15:05:10

Nie mogę jeszcze zostawić komentarza, więc zamieszczę jako osobną odpowiedź.

Rozwiązanie oparte na logarytmie nie oblicza prawidłowej liczby cyfr dla bardzo dużych długich liczb całkowitych, na przykład:

long n = 99999999999999999L;

// correct answer: 17
int numberOfDigits = String.valueOf(n).length();

// incorrect answer: 18
int wrongNumberOfDigits = (int) (Math.log10(n) + 1); 

Rozwiązanie oparte na Logarytmie oblicza niepoprawną liczbę cyfr w dużych liczbach całkowitych

 3
Author: moodcheerful,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41

A może zwykła stara Matematyka? Podziel przez 10, aż osiągniesz 0.

public static int getSize(long number) {
        int count = 0;
        while (number > 0) {
            count += 1;
            number = (number / 10);
        }
        return count;
    }
 2
Author: Sinista,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-09 18:12:00

Rozwiązanie Mariana, teraz z Ternary:

 public int len(int n){
        return (n<100000)?((n<100)?((n<10)?1:2):(n<1000)?3:((n<10000)?4:5)):((n<10000000)?((n<1000000)?6:7):((n<100000000)?8:((n<1000000000)?9:10)));
    }

ponieważ możemy.

 2
Author: UserNotFound,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-01 13:18:27

Ciekawe, próbowałem to porównać ...

import org.junit.Test;
import static org.junit.Assert.*;


public class TestStack1306727 {

    @Test
    public void bench(){
        int number=1000;
        int a= String.valueOf(number).length();
        int b= 1 + (int)Math.floor(Math.log10(number));

        assertEquals(a,b);
        int i=0;
        int s=0;
        long startTime = System.currentTimeMillis();
        for(i=0, s=0; i< 100000000; i++){
            a= String.valueOf(number).length();
            s+=a;
        }
        long stopTime = System.currentTimeMillis();
        long runTime = stopTime - startTime;
        System.out.println("Run time 1: " + runTime);
        System.out.println("s: "+s);
        startTime = System.currentTimeMillis();
        for(i=0,s=0; i< 100000000; i++){
            b= number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));
            s+=b;
        }
        stopTime = System.currentTimeMillis();
        runTime = stopTime - startTime;
        System.out.println("Run time 2: " + runTime);
        System.out.println("s: "+s);
        assertEquals(a,b);


    }
}

Wyniki są następujące:

Run time 1: 6765
s: 400000000
Run time 2: 6000
s: 400000000

Teraz zastanawiam się, czy mój benchmark rzeczywiście coś znaczy, ale uzyskuję spójne wyniki (zmiany w ms) w wielu przebiegach samego benchmarka ... :) Wygląda na to, że nie ma sensu próbować tego zoptymalizować...


Edit: po komentarzu ptomli, w powyższym kodzie zamieniłem "numer" na " i " i otrzymałem następujące wyniki po 5 biegach ławki:

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11485
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11469
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11484
s: 788888890
Run time 2: 8547
s: 788888890
 1
Author: Jean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-20 15:33:14

A co z tą metodą rekurencyjną?

    private static int length = 0;

    public static int length(int n) {
    length++;
    if((n / 10) < 10) {
        length++;
    } else {
        length(n / 10);
    }
    return length;
}
 0
Author: Jedi Dula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-20 14:05:02

Proste rozwiązanie:

public class long_length {
    long x,l=1,n;
    for (n=10;n<x;n*=10){
        if (x/n!=0){
            l++;
        }
    }
    System.out.print(l);
}
 0
Author: mikegh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-29 23:26:08

Naprawdę proste rozwiązanie:

public int numLength(int n) {
  for (int length = 1; n % Math.pow(10, length) != n; length++) {}
  return length;
}
 0
Author: VoidCatz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-23 22:43:08

Lub zamiast długości możesz sprawdzić, czy liczba jest większa lub mniejsza, a następnie żądana liczba.

    public void createCard(int cardNumber, int cardStatus, int customerId) throws SQLException {
    if(cardDao.checkIfCardExists(cardNumber) == false) {
        if(cardDao.createCard(cardNumber, cardStatus, customerId) == true) {
            System.out.println("Card created successfully");
        } else {

        }
    } else {
        System.out.println("Card already exists, try with another Card Number");
        do {
            System.out.println("Enter your new Card Number: ");
            scan = new Scanner(System.in);
            int inputCardNumber = scan.nextInt();
            cardNumber = inputCardNumber;
        } while(cardNumber < 95000000);
        cardDao.createCard(cardNumber, cardStatus, customerId);
    }
}

}

 0
Author: Szabi Zsoldos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 14:15:49

Nie widziałem jeszcze rozwiązania opartego na mnożeniu. Logarytm, dzielenie i rozwiązania oparte na łańcuchach staną się raczej nieporęczne wobec milionów przypadków testowych, więc oto jeden dla ints:

/**
 * Returns the number of digits needed to represents an {@code int} value in 
 * the given radix, disregarding any sign.
 */
public static int len(int n, int radix) {
    radixCheck(radix); 
    // if you want to establish some limitation other than radix > 2
    n = Math.abs(n);

    int len = 1;
    long min = radix - 1;

    while (n > min) {
        n -= min;
        min *= radix;
        len++;
    }

    return len;
}

W bazie 10 działa to, ponieważ N jest zasadniczo porównywane do 9, 99, 999... / min wynosi 9,90,900... a n jest odejmowane przez 9, 90, 900...

Niestety, nie jest to przenośne do long tylko przez zastąpienie każdej instancji int z powodu przepełnienia. Z drugiej strony, to po prostu tak się składa, że będzie działać dla baz 2 i 10 (ale w większości innych baz nie działa). Będziesz potrzebował tabeli wyszukiwania dla punktów przepełnienia (lub testu podziału... ew)

/**
 * For radices 2 &le r &le Character.MAX_VALUE (36)
 */
private static long[] overflowpt = {-1, -1, 4611686018427387904L,
    8105110306037952534L, 3458764513820540928L, 5960464477539062500L,
    3948651115268014080L, 3351275184499704042L, 8070450532247928832L,
    1200757082375992968L, 9000000000000000000L, 5054470284992937710L,
    2033726847845400576L, 7984999310198158092L, 2022385242251558912L,
    6130514465332031250L, 1080863910568919040L, 2694045224950414864L,
    6371827248895377408L, 756953702320627062L, 1556480000000000000L,
    3089447554782389220L, 5939011215544737792L, 482121737504447062L,
    839967991029301248L, 1430511474609375000L, 2385723916542054400L,
    3902460517721977146L, 6269893157408735232L, 341614273439763212L,
    513726300000000000L, 762254306892144930L, 1116892707587883008L,
    1617347408439258144L, 2316231840055068672L, 3282671350683593750L,
    4606759634479349760L};

public static int len(long n, int radix) {
    radixCheck(radix);
    n = abs(n);

    int len = 1;
    long min = radix - 1;
    while (n > min) {
        len++;
        if (min == overflowpt[radix]) break;
        n -= min;
        min *= radix;

    }

    return len;
}
 0
Author: Jonathan Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-10 13:11:08

Z projektem (opartym na problemie). To alternatywa dzielenia i zwyciężania. Najpierw zdefiniujemy enum (biorąc pod uwagę, że dotyczy to tylko niepodpisanej liczby całkowitej).

public enum IntegerLength {
    One((byte)1,10),
    Two((byte)2,100),
    Three((byte)3,1000),
    Four((byte)4,10000),
    Five((byte)5,100000),
    Six((byte)6,1000000),
    Seven((byte)7,10000000),
    Eight((byte)8,100000000),
    Nine((byte)9,1000000000);

    byte length;
    int value;

    IntegerLength(byte len,int value) {
        this.length = len;
        this.value = value;
    }

    public byte getLenght() {
        return length;
    }

    public int getValue() {
        return value;
    }
}

Teraz zdefiniujemy klasę, która przechodzi przez wartości z enum i porównamy i zwrócimy odpowiednią długość.

public class IntegerLenght {
    public static byte calculateIntLenght(int num) {    
        for(IntegerLength v : IntegerLength.values()) {
            if(num < v.getValue()){
                return v.getLenght();
            }
        }
        return 0;
    }
}
Czas działania tego rozwiązania jest taki sam jak w przypadku podejścia "divide-and-conquer".
 0
Author: androider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 15:15:14

Wprowadź numer i utwórz Arraylist, a pętla while zapisze wszystkie cyfry do Arraylist. Następnie możemy wyjąć rozmiar tablicy, która będzie długością wprowadzonej wartości całkowitej.

ArrayList<Integer> a=new ArrayList<>();

while(number > 0) 
{ 
    remainder = num % 10; 
    a.add(remainder);
    number = number / 10; 
} 

int m=a.size();
 0
Author: dev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 15:19:34

Łatwy sposób rekurencyjny

int    get_int_lenght(current_lenght, value)
{
 if (value / 10 < 10)
    return (current_lenght + 1);
return (get_int_lenght(current_lenght + 1, value))
}

Nie testowane

 0
Author: Valérian Polizzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 15:21:45

Możemy to osiągnąć za pomocą pętli rekurencyjnej

    public static int digitCount(int numberInput, int i) {
        while (numberInput > 0) {
        i++;
        numberInput = numberInput / 10;
        digitCount(numberInput, i);
        }
        return i;
    }

    public static void printString() {
        int numberInput = 1234567;
        int digitCount = digitCount(numberInput, 0);

        System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
    }
 0
Author: ericdemo07,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-21 05:13:48

Kolejne podejście ciągów. Krótkie i słodkie - dla dowolnej liczby całkowitej n.

int length = ("" + n).length();
 0
Author: ThisClark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-04 21:10:13
    int num = 02300;
    int count = 0;
    while(num>0){
         if(num == 0) break;
         num=num/10;
         count++;
    }
    System.out.println(count);
 -1
Author: kanakangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-10 08:38:09

Oto bardzo prosta metoda, którą stworzyłem, która działa dla dowolnej liczby:

public static int numberLength(int userNumber) {

    int numberCounter = 10;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        int numberRatio = userNumber / numberCounter;
        if (numberRatio < 1) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }

    return digitLength; 
}

Sposób działania jest ze zmienną licznika liczb jest taki, że 10 = 1 przestrzeń cyfr. Na przykład .1 = 1 dziesiąta = > 1 przestrzeń cyfr. Dlatego jeśli masz int number = 103342; otrzymasz 6, ponieważ jest to odpowiednik .0000010000 Czy ktoś ma lepszą nazwę zmiennej dla numberCounter? Nie mogę wymyślić nic lepszego.

Edit: pomyślałem o lepszym wyjaśnieniu. Zasadniczo co robi pętla while dzielisz liczbę przez 10, aż będzie mniejsza niż 1. Zasadniczo, kiedy dzielisz coś przez 10, przenosisz to z powrotem o jedną przestrzeń liczbową, więc po prostu dzielisz to przez 10, aż osiągniesz

Oto kolejna wersja, która może liczyć ilość liczb w dziesiętnym:

public static int repeatingLength(double decimalNumber) {

    int numberCounter = 1;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        double numberRatio = decimalNumber * numberCounter;

        if ((numberRatio - Math.round(numberRatio)) < 0.0000001) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }
    return digitLength - 1;
}
 -1
Author: Andrew Patterson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 15:25:59

Ktoś chce to zrobić głównie dlatego, że chce to "zaprezentować", co głównie oznacza, że w końcu musi być" toString-ed " (lub przekształcone w inny sposób) jawnie lub niejawnie; zanim może być zaprezentowane (na przykład wydrukowane).

Jeśli tak jest, to po prostu spróbuj uczynić niezbędny" toString " jawnym i policz bity.

 -1
Author: howToDeleteMyAccount,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-03 03:57:22

Można było cyfry używając kolejnych podziałów przez dziesięć:

int a=0;

if (no < 0) {
    no = -no;
} else if (no == 0) {
    no = 1;
}

while (no > 0) {
    no = no / 10;
    a++;
}

System.out.println("Number of digits in given number is: "+a);
 -2
Author: user1590262,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-09 12:46:31

Spróbuj przekonwertować int na string, a następnie uzyskaj długość string. To powinno mieć długość int .

public static int intLength(int num){
    String n = Integer.toString(num);
    int newNum = n.length();
    return newNum;
}
 -2
Author: user5458400,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-18 00:49:01