How to Find Length of Integer in 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:
Let's discuss one by one. Using while loopWe 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 StringAnother 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 MultiplicationWe 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 LogarithmWe 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 RecursionWe 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
Next TopicJava 8 filters
