Since the number of digits in base 10 of an integer is just 1 + truncate(log10(number)), you can do:
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 because my last edit fixed the code example, but not the description.
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+"]");
}
Enter the number and create an Arraylist, and the while loop will record all the digits into the Arraylist. Then we can take out the size of array, which will be the length of the integer value you entered.
ArrayList<Integer> a=new ArrayList<>();
while(number > 0)
{
remainder = num % 10;
a.add(remainder);
number = number / 10;
}
int m=a.size();
Since the number of digits in base 10 of an integer is just 1 + truncate(log10(number)), you can do:
Edited because my last edit fixed the code example, but not the description.
With design (based on problem). This is an alternate of divide-and-conquer. We'll first define an enum (considering it's only for an unsigned int).
Now we'll define a class that goes through the values of the enum and compare and return the appropriate length.
The run time of this solution is the same as the divide-and-conquer approach.
We can achieve this using a recursive loop
Enter the number and create an
Arraylist
, and the while loop will record all the digits into theArraylist
. Then we can take out the size of array, which will be the length of the integer value you entered.A really simple solution:
The logarithm is your friend:
NB: only valid for n > 0.