To find the number of digits in an integer you can use one of the following methods: **(1) Use Iteration (2) Use str()+len() functions (3) Use int(math.log10(x)) +1 (4) Use Recursion**

**Problem Formulation**

**Given:**An integer value.**Question:**Find the number of digits in the integer/number given.

**Test Cases:**

Input: num = 123Output:3 =========================================Input:num = -123Output:3 =========================================Input:num = 0Output:1

**Method 1: Iterative Approach**

**Approach: **

- Use the built-in
`abs()`

method to derive the absolute value of the integer. This is done to take care of negative integer values entered by the user. - If the value entered is 0 then return 1 as the output. Otherwise, follow the next steps.
- Initialize a counter variable that will be used to count the number of digits in the integer.
- Use a while loop to iterate as long as the number is greater than 0. To control the iteration condition, ensure that the number is stripped of its last digit in each iteration. This can be done by performing a floor division (
`num//10`

) in each iteration. This will make more sense when you visualize the tabular dry run of the code given below. - Every time the while loop satisfies the condition for iteration, increment the value of the counter variable. This ensures that the count of each digit in the integer gets taken care of with the help of the counter variable.

**Code:**

num = int(input("Enter an Integer: ")) num = abs(num) digit_count = 0 if num == 0: print("Number of Digits: ", digit_count) else: while num != 0: num //= 10 digit_count += 1 print("Number of Digits: ", digit_count)

**Output: **

Test Case 1:Enter an Integer: 123 Number of Digits: 3Test Case 2:Enter an Integer: -123 Number of Digits: 3Test Case 3:Enter an Integer: 0 Number of Digits: 1

**Explanation through tabular dry run:**

💎**Readers Digest:**

Python’s built-in

function returns the absolute value of the argument **abs(x)**`x`

that can be an integer, float, or object implementing the `__abs__()`

function. For a complex number, the function returns its magnitude. The absolute value of any numerical input argument `-x`

or `+x`

is the corresponding positive value `+x`

. Read more **here**.

**Method 2: Using str() and ****len**()

**Approach: **Convert the given integer to a string using Python’s `str()`

function. Then find the length of this string which will return the number of characters present in it. In this case, the number of characters is essentially the number of digits in the given number.

To deal with negative numbers, you can use the `abs()`

function to derive its absolute value before converting it to a string. Another workaround is to check if the number is a negative number or not and return the length accordingly, as shown in the following code snippet.

**Code:**

num = int(input("Enter an Integer: ")) if num >= 0: digit_count = len(str(num)) else: digit_count = len(str(num)) - 1 # to eliminate the - sign print("Number of Digits: ", digit_count)

**Output:**

Test Case 1:

Enter an Integer: 123

Number of Digits: 3Test Case 2:

Enter an Integer: -123

Number of Digits: 3Test Case 3:

Enter an Integer: 0

Number of Digits: 1

**Alternate Formulation: **Instead of using `str(num)`

, you can also use *string modulo* as shown below:

num = abs(int(input("Enter an Integer: "))) digit_count = len('%s'%num) print("Number of Digits: ", digit_count)

**Method 3: Using math Module**

**Disclaimer:** This approach works if the given number is less than 999999999999998. This happens because the float value returned has too many .9s in it which causes the result to round up.

**Prerequisites: **To use the following approach to solve this question, it is essential to have a firm grip on a couple of functions:

**math.log10(x)**– Simply put this function returns a float value representing the base 10 logarithm of a given number.

**Example:**

2. **int(x)** – It is a built-in function in Python that converts the passed argument x to an integer value. For example, `int('24')`

converts the passed string value `'24'`

into an integer number and returns `24`

as the output. Note that the `int()`

function on a float argument rounds it down to the closest integer.

**Example:**

**Approach: **

- Use the
`math.log(num)`

function to derive the base 10 logarithm value of the given integer. This value will be a floating-point number. Hence, convert this to an integer. - As a matter of fact, when the result of the base 10 logarithm representation of a value is converted to its integer representation, then the integer value returned will almost most certainly be an integer value that is 1 less than the number of digits in the given number.
- Thus add 1 to the value returned after converting the base 10 logarithm value to an integer to yield the desired output.
- To take care of conditions where:
- Given number = 0 : return 1 as the output.
- Given number < 0 : negate the given number to ultimately convert it to its positive magnitude as:
`int(math.log10(-num))`

.

**Code:**

import math num = int(input("Enter an Integer: ")) if num > 0: digit_count = int(math.log10(num))+1 elif num == 0: digit_count = 1 else: digit_count = int(math.log10(-num))+1 print("Number of Digits: ", digit_count)

**Output:**

Test Case 1:

Enter an Integer: 123

Number of Digits: 3Test Case 2:

Enter an Integer: -123

Number of Digits: 3Test Case 3:

Enter an Integer: 0

Number of Digits: 1

**Method 4: Using Recursion**

Recursion is a powerful coding technique that allows a function or an algorithm to call itself again and again until a base condition is satisfied. Thus, we can use this technique to solve our question.

**Code**:

def count_digits(n): if n < 10: return 1 return 1 + count_digits(n / 10) num = int(input("Enter an Integer: ")) num = abs(num) print(count_digits(num))

**Output:**

Test Case 1:

Enter an Integer: 123

Number of Digits: 3Test Case 2:

Enter an Integer: -123

Number of Digits: 3Test Case 3:

Enter an Integer: 0

Number of Digits: 1

**Exercise**

**Question: **Given a string. How will you cont the number of digits, letters, spaces and other characters in the string?

**Solution:**

text = 'Python Version 3.0' digits = sum(x.isdigit() for x in text) letters = sum(x.isalpha() for x in text) spaces = sum(x.isspace() for x in text) others = len(text) - digits - letters - spaces print(f'No. of Digits = {digits}') print(f'No. of Letters = {letters}') print(f'No. of Spaces = {spaces}') print(f'No. of Other Characters = {others}')

**Output:**

```
No. of Digits = 2
No. of Letters = 13
No. of Spaces = 2
No. of Other Characters = 1
```

**Explanation: **Check if each character in the given string is a digit or a letter or a space or any other character or not using built-in Python functions. In each case find the cumulative count of each type with the help of the `sum()`

method. To have a better grip on whats happening in the above code it is essential to understand the different methods that have been used to solve the question.

**isdigit()**: Checks whether all characters in a given are digits, i.e., numbers from 0 to 9 (`True`

or`False`

).**isalpha():**Checks whether all charactersof a given string are alphabetic (`True`

or`False`

).**isspace():**Checks whether all characters are whitespaces (`True`

or`False`

).**sum()**: returns the sum of all items in a given iterable.

## Conclusion

We have discussed as many as four different ways of finding number of digits in an integer. We also solved a similar exercise to enhance our skills. I hope you enjoyed this question and it helped to sharpen your coding skills. Please **stay tuned** and **subscribe** for more interesting coding problems.

**Recommended Read: Coding Interview Questions**

**Recommended: ****Finxter Computer Science Academy**

- One of the most sought-after skills on Fiverr and Upwork is
**web scraping**. Make no mistake:is a critical life skill in today’s world that’s shaped by the web and remote work.**extracting data programmatically from websites** - So, do you want to master the art of web scraping using Python’s BeautifulSoup?
- If the answer is yes – this course will take you from beginner to expert in Web Scraping.