From 22e2e74bf8149a525d06a01f0fe870fadc2bce71 Mon Sep 17 00:00:00 2001 From: shellhub Date: Wed, 12 Aug 2020 22:51:19 +0800 Subject: [PATCH] add NumberOfDigits --- Maths/NumberOfDigits.java | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Maths/NumberOfDigits.java diff --git a/Maths/NumberOfDigits.java b/Maths/NumberOfDigits.java new file mode 100644 index 00000000..9e760727 --- /dev/null +++ b/Maths/NumberOfDigits.java @@ -0,0 +1,62 @@ +package Maths; + +/** + * Find the number of digits in a number. + */ +public class NumberOfDigits { + public static void main(String[] args) { + int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789}; + for (int i = 0; i < numbers.length; ++i) { + assert numberOfDigits(numbers[i]) == i + 1; + assert numberOfDigitsFast(numbers[i]) == i + 1; + assert numberOfDigitsFaster(numbers[i]) == i + 1; + assert numberOfDigitsRecursion(numbers[i]) == i + 1; + } + } + + /** + * Find the number of digits in a number. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigits(int number) { + int digits = 0; + do { + digits++; + number /= 10; + } while (number != 0); + return digits; + } + + /** + * Find the number of digits in a number fast version. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsFast(int number) { + return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); + } + + + /** + * Find the number of digits in a number faster version. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsFaster(int number) { + return number < 0 ? (-number + "").length() : (number + "").length(); + } + + /** + * Find the number of digits in a number using recursion. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsRecursion(int number) { + return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10); + } +}