Как найти длину числа java

In this section, we will learn the different approaches to find the length of an integer in Java. The length of an integer means the total number of digits present in that integer.

We can find the length of integer by using the following approaches:

  • Using while loop
  • Using String
  • Using Continuous Multiplication
  • Using Logarithm
  • Using Recusion

Let’s discuss one by one.

Using while loop

We can find the length of an integer using a while loop. Observe the following code.

FileName: IntegerLengthExample.java

Output:

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

Using String

Another idea can be to convert the number into a string and then compute its size. The size of the string gives the length of the string. The following program depicts the same.

FileName: IntegerLengthExample1.java

Output:

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

Using Continuous Multiplication

We can multiply a number 1 by 10 until it becomes greater than the number n. Each time we multiply by 10, we increment a variable count by 1. The final value of the count gives the length of the integer n. Let’s understand it with the help of the following program.

FileName: IntegerLengthExample2.java

Output:

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

Using Logarithm

We can also use log to find the length of an integer. Observe the following program.

FileName: IntegerLengthExample3.java

Output:

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

Using Recursion

We can also use recursion to find out the length of an integer. The following program demonstrates the same.

FileName: IntegerLengthExample4.java

Output:

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

Ответы

Аватар пользователя Maksim Litvinov

Maksim Litvinov

15 июня 2022

Самый простой способ узнать длину числа в Java – это вариант решения через строки. Нужно преобразовать число в строку и узнать длину строки. Рассмотрим на примере:

var num = 234;

var length = String.valueOf(num).length();

System.out.println(length); // => 3



0



0

Добавьте ваш ответ

Рекомендуемые курсы

курс

Java: Автоматическое тестирование

14 часов

Старт в любое время

курс

Java: Введение в ООП

11 часов

Старт в любое время

курс

Java: Основы ООП

35 часов

Старт в любое время

Похожие вопросы

Как узнать длину string java


23 ноября 2021

1

ответ

Как найти длину числа в java


21 декабря 2021

1

ответ

Как узнать длину массива java


21 декабря 2021

1

ответ

Как узнать длину строки java


21 декабря 2021

1

ответ

I haven’t seen a multiplication-based solution yet. Logarithm, divison, and string-based solutions will become rather unwieldy against millions of test cases, so here’s one for 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;
}

In base 10, this works because n is essentially being compared to 9, 99, 999… as min is 9, 90, 900… and n is being subtracted by 9, 90, 900…

Unfortunately, this is not portable to long just by replacing every instance of int due to overflow. On the other hand, it just so happens it will work for bases 2 and 10 (but badly fails for most of the other bases). You’ll need a lookup table for the overflow points (or a division test… 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;
}

  1. HowTo
  2. Java Howtos
  3. Calculate Length of Integer in Java
  1. Use the for Loop to Calculate the Length of an Integer in Java
  2. Use the Math.log10() Function to Calculate the Length of an Integer in Java
  3. Use the toString() Function to Calculate the Length of an Integer in Java

Calculate Length of Integer in Java

In this tutorial, we calculate the number of digits in an integer in Java.

Use the for Loop to Calculate the Length of an Integer in Java

First, we will see a simple iterative solution for this. We will divide the integer by 10, storing the count in each iteration until the number equals zero.

The below code demonstrates the above method.

public class Digits {
    static int count_digit(int x)
    {
        int count = 0;
        while (x != 0) {
            x = x / 10;
            ++count;
        }
        return count;
    }
    public static void main(String[] args)
    {
        int x = 345;
        System.out.print(count_digit(x));
    }
}

Output:

We can also implement the above logic using a divide and conquer with recursion.

Use the Math.log10() Function to Calculate the Length of an Integer in Java

Now let’s see the log-based solution for this. We will be using the logarithm of base 10 for counting the number of the digits in an integer. This method will work only on positive integers. We will be importing the java.util class from which we will use the Math.log10() function.

See the code below.

import java.util.*;
 
public class Digits {
 
    static int count_digit(int x)
    {
        return (int)Math.floor(Math.log10(x) + 1);
    }
 
    public static void main(String[] args)
    {
        int x = 345;
        System.out.print(count_digit(x));
    }
}    

Output:

Use the toString() Function to Calculate the Length of an Integer in Java

Another method is to change the integer into a string and then calculate its length. We will use the toString() function from the java.util package to convert the integer to a string. The length() method returns the length of the string.

The below code demonstrate the above code.

import java.util.*;
public class Digits {
    static void count_digits(int x)
    {
        String dig = Integer.toString(x);
        System.out.println(+dig.length());
    }
    public static void main(String args[])
    {
        int x = 345;
        count_digits(x);
    }
}

Output:

Related Article — Java Int

  • Convert Int to Char in Java
  • Convert Int to Double in Java
  • Convert Object to Int in Java
  • List of Ints in Java
  • Convert Integer to Int in Java
  • Check if Int Is Null in Java

Автор оригинала: baeldung.

1. введение

В этом кратком руководстве мы рассмотрим различные способы получения количества цифр в целочисленном в Java.

Мы также проанализируем эти различные методы и выясним, какой алгоритм лучше всего подходит для нашей ситуации.

Дальнейшее чтение:

Проверьте, является ли строка Числовой в Java

Практическое руководство по десятичному формату

2. Количество цифр в целочисленном числе

Для методов, обсуждаемых здесь, мы рассматриваем только положительные целые числа. Если мы ожидаем каких-либо отрицательных входных данных, то мы можем сначала использовать Math.abs(число) перед использованием любого из этих методов.

2.1. Решение На основе строк

Возможно , самый простой способ получить количество цифр в Integer – это преобразовать его в String и вызвать метод length () . Это вернет длину Строки представления нашего числа:

int length = String.valueOf(number).length();

Но это может быть неоптимальным подходом, так как этот оператор включает выделение памяти для строки для каждой оценки . JVM должен сначала проанализировать наш номер и скопировать его цифры в отдельную Строку , А также выполнить ряд различных операций (например, сохранение временных копий, обработка преобразований Юникода и т. Д.).

Если у нас есть только несколько чисел для оценки, то мы можем явно пойти с этим решением – потому что разница между этим и любым другим подходом будет пренебрегаться даже для больших чисел.

2.2. Логарифмический Подход

Для чисел, представленных в десятичной форме, если мы возьмем их логин в базе 10 и округлим его, то получим количество цифр в этом числе:

int length = (int) (Math.log10(number) + 1);

Обратите внимание, что log 10 0 какого-либо числа не определено. Итак, если мы ожидаем каких-либо входных данных со значением 0 , тогда мы можем проверить и это.

Логарифмический подход значительно быстрее, чем подход на основе String , поскольку ему не нужно проходить процесс преобразования данных. Это просто включает в себя простой, простой расчет без какой-либо дополнительной инициализации объекта или циклов.

2.3. Повторное Умножение

В этом методе мы возьмем временную переменную (инициализированную в 1) и будем непрерывно умножать ее на 10, пока она не станет больше нашего числа. Во время этого процесса мы также будем использовать переменную length , которая будет отслеживать длину числа:

int length = 0;
long temp = 1;
while (temp <= number) {
    length++;
    temp *= 10;
}
return length;

В этом коде строка temp совпадает с записью temp = (temp << 3) + (temp << 1) . Поскольку умножение обычно является более дорогостоящей операцией на некоторых процессорах по сравнению с операторами сдвига, последние могут быть немного более эффективными.

2.4. Деление на две степени

Если мы знаем о диапазоне нашего числа, то мы можем использовать вариацию, которая еще больше сократит наши сравнения. Этот метод делит число на степени двух (например, 1, 2, 4, 8 и т. Д.):

Этот метод делит число на степени двух (например, 1, 2, 4, 8 и т. Д.):

int length = 1;
if (number >= 100000000) {
    length += 8;
    number /= 100000000;
}
if (number >= 10000) {
    length += 4;
    number /= 10000;
}
if (number >= 100) {
    length += 2;
    number /= 100;
}
if (number >= 10) {
    length += 1;
}
return length;

Он использует тот факт, что любое число может быть представлено сложением степеней 2. Например, 15 можно представить в виде 8+4+2+1, которые все являются степенями 2.

Для 15-значного числа мы бы провели 15 сравнений в нашем предыдущем подходе, который мы сократили до 4 в этом методе.

2.5. Разделяй и властвуй

Это, возможно, самый громоздкий подход по сравнению со всеми другими, описанными здесь, но излишне говорить, этот самый быстрый , потому что мы не выполняем никакого типа преобразования, умножения, сложения или инициализации объекта.

Мы получаем наш ответ всего в трех или четырех простых утверждениях if :

if (number < 100000) {
    if (number < 100) {
        if (number < 10) {
            return 1;
        } else {
            return 2;
        }
    } else {
        if (number < 1000) {
            return 3;
        } else {
            if (number < 10000) {
                return 4;
            } else {
                return 5;
            }
        }
    }
} else {
    if (number < 10000000) {
        if (number < 1000000) {
            return 6;
        } else {
            return 7;
        }
    } else {
        if (number < 100000000) {
            return 8;
        } else {
            if (number < 1000000000) {
                return 9;
            } else {
                return 10;
            }
        }
    }
}

Подобно предыдущему подходу, мы можем использовать этот метод только в том случае, если мы знаем о диапазоне нашего числа.

3. Бенчмаркинг

Теперь, когда у нас есть хорошее понимание потенциальных решений, давайте проведем простой бенчмаркинг всех наших методов с использованием жгута Java Microbenchmark (JMH) .

В следующей таблице показано среднее время обработки каждой операции (в наносекундах):

Benchmark                            Mode  Cnt   Score   Error  Units
Benchmarking.stringBasedSolution     avgt  200  32.736 ± 0.589  ns/op
Benchmarking.logarithmicApproach     avgt  200  26.123 ± 0.064  ns/op
Benchmarking.repeatedMultiplication  avgt  200   7.494 ± 0.207  ns/op
Benchmarking.dividingWithPowersOf2   avgt  200   1.264 ± 0.030  ns/op
Benchmarking.divideAndConquer        avgt  200   0.956 ± 0.011  ns/op

Решение на основе String , которое является самым простым, также является самой дорогостоящей операцией, поскольку это единственная операция, которая требует преобразования данных и инициализации новых объектов.

Логарифмический подход значительно более эффективен по сравнению с предыдущим решением, поскольку он не требует преобразования данных. И, будучи однострочным решением, это может быть хорошей альтернативой подходу на основе String – .

Повторное умножение включает в себя простое умножение, пропорциональное длине числа; например, если число состоит из пятнадцати цифр, то этот метод будет включать в себя пятнадцать умножений.

Однако самый следующий метод использует тот факт, что каждое число может быть представлено степенями двух (подход, аналогичный BCD), и сводит то же самое к 4 операциям деления, поэтому он еще более эффективен, чем первый.

Наконец, как мы можем заключить, наиболее эффективным алгоритмом является многословная реализация “Разделяй и властвуй” , которая дает ответ всего в трех или четырех простых операторах if. Мы можем использовать его, если у нас есть большой набор данных чисел, которые нам нужно проанализировать.

4. Заключение

В этой краткой статье мы описали некоторые из способов найти количество цифр в целочисленном и сравнили эффективность каждого подхода.

И, как всегда, вы можете найти полный код на GitHub .

Понравилась статья? Поделить с друзьями:
  • Как найти дежурную больницу
  • Как найти маяки в штукатурке
  • Как нагадать найти любимого
  • Как решить найдите значение выражения огэ
  • Как найти формулу толщину в физике