📜 ⬆️ ⬇️

Ways to find the number of digits in the number

With high probability we can assume that every programmer had at least once such a task. There are many ways to find the number of digits. The article will present several functions from the most banal, and not very.

1. Line length

Quite a banal way - is finding the length of the line. This is not the fastest way, but it is suitable for very simple tasks.
')
public int getCountsOfDigits(long number) { return String.valueOf(Math.abs(number)).length(); } 

2. Cycle with division

A common method whose speed linearly depends on the length of a number.

  public int getCountsOfDigits(long number) { int count = (number == 0) ? 1 : 0; while (number != 0) { count++; number /= 10; } return count; } 


3. Decimal logarithm and rounding

The logarithm works in constant time, the advantage of which is on large numbers.

 public static int getCountsOfDigits(long number) { return(number == 0) ? 1 : (int) Math.ceil(Math.log10(Math.abs(number) + 0.5)); } 

You can use not only Math.ceil, this is just one of the options for using the logarithm.

4. Comparison

A quick but not practical way due to the amount of code just for int took 38 lines. Of course there are craftsmen who can make more beautiful and clearer. I will not leave the code for long, but leave it for int, but I think the principle is clear.

Code
  public static int getCountsOfDigits(int n) { if (n < 100000) { if (n < 100) { if (n < 10) { return 1; } else { return 2; } } else { if (n < 1000) { return 3; } else { if (n < 10000) { return 4; } else { return 5; } } } } else { if (n < 10000000) { if (n < 1000000) { return 6; } else { return 7; } } else { if (n < 100000000) { return 8; } else { if (n < 1000000000) { return 9; } else { return 10; } } } } } 


Rating looks like this:
1. Comparisons (show the best result)
2. Logarithm
3. Division
4. String (worst result)

Source: https://habr.com/ru/post/269237/


All Articles