Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of digits in an int value? [duplicate]

Tags:

java

arrays

Given the following code.

 int[] eg = {21,20,1,12,2}
 public numbers(int[] eg)
 {
     for(int i=0; i < eg.length; i++)

I would expect eg.length to be 5, where eg[0] would = 21 eg[1] would = 20, eg[3] would = 1

I would like to check each element of eg[i] to see if it is a 1 digit or 2 digit number I tried eg[0].length to no avail, but am I correct in assuming that is only for Array Lists?

like image 920
30iT Avatar asked May 23 '15 08:05

30iT


4 Answers

Convert the number to a String and get the length.

int length = String.valueOf(eg[i]).length();

Or

int length = Integer.valueOf(eg[i]).toString().length();

Use this mathematical equation (assuming that all the data in the array are strictly positive numbers).

int length = (int)(Math.log10(eg[i])+1);
like image 182
MChaker Avatar answered Sep 19 '22 05:09

MChaker


eg[i] is of type int, which doesn't have the length property.

There are many ways of telling how many digits the number has:

  • write your own method that accepts an int and keeps dividing by 10 until the number reaches 0.

  • using math properties:

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

  • converting the number to String and using its methods

like image 34
Maroun Avatar answered Sep 19 '22 05:09

Maroun


If you want to see what is the number length, MChaker's solution is the correct one. However, if you want to see if the number contains one digit or more than one digit, then you might consider the following solution:

public class NumberTest {
public static void main(String[] args) {
    int[] eg = {21,20,1,12,2, -3, -8, -20};
    System.out.println("Array Length: " + eg.length);

    for(int i=0; i < eg.length; i++) {
        System.out.println("#" + i + ": Value: " + eg[i] + " one digit number: " + isOneDigitNumber(eg[i]));
    }
}
static private boolean isOneDigitNumber(int number) {
    return (-10 < number && number < 10);
}

}

and here is the result of above code:

Array Length: 8
#0: Value: 21 one digit number: false
#1: Value: 20 one digit number: false
#2: Value: 1 one digit number: true
#3: Value: 12 one digit number: false
#4: Value: 2 one digit number: true
#5: Value: -3 one digit number: true
#6: Value: -8 one digit number: true
#7: Value: -20 one digit number: false
#7: Value: -20 one digit number: false
like image 43
Hoa Nguyen Avatar answered Sep 21 '22 05:09

Hoa Nguyen


There's an algorithm used in JDK which is probably the fastest one:

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;
}
like image 21
Tagir Valeev Avatar answered Sep 23 '22 05:09

Tagir Valeev