Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[-]
Welcome
You have to register before you can post on our site.

Username:


Password:





[-]
Discord Widget

[-]
Twitter: SickGaming

[-]
Latest Threads
[Tut] 3 Simple Steps to Convert calendar...
Last Post: xSicKxBot
Today 12:58 AM
» Replies: 0
» Views: 0
[Tut] Add Google reCaptcha V3 Example wi...
Last Post: xSicKxBot
Today 12:58 AM
» Replies: 0
» Views: 0
(Free Game Key) Cook, Serve, Delicious! ...
Last Post: xSicKxBot
Today 12:58 AM
» Replies: 0
» Views: 0
PC - Frogun
Last Post: xSicKxBot
Today 12:57 AM
» Replies: 0
» Views: 0
[Tut] How to Sort Words Alphabetically i...
Last Post: xSicKxBot
Yesterday 05:51 AM
» Replies: 0
» Views: 0
PC - The Sims 4: High School Years
Last Post: xSicKxBot
Yesterday 05:51 AM
» Replies: 0
» Views: 0
News - Edgar Allan Poe Horror Biopic Rav...
Last Post: xSicKxBot
Yesterday 05:51 AM
» Replies: 0
» Views: 0
[Oracle Blog] Announcing GraalVM Enterpr...
Last Post: xSicKxBot
08-10-2022 12:05 PM
» Replies: 0
» Views: 0
[Tut] Best Solidity Linter
Last Post: xSicKxBot
08-10-2022 12:05 PM
» Replies: 0
» Views: 0
[Tut] JavaScript Autocomplete TextBox (a...
Last Post: xSicKxBot
08-10-2022 12:05 PM
» Replies: 0
» Views: 0

[Tut] How to Find Number of Digits in an Integer?

#1
How to Find Number of Digits in an Integer?

Rate this post

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 = 123
Output: 3
=========================================
Input:
num = -123
Output: 3
=========================================
Input: num = 0
Output: 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: 3 Test Case 2:
Enter an Integer: -123
Number of Digits: 3 Test Case 3:
Enter an Integer: 0
Number of Digits: 1

Explanation through tabular dry run:


💎Readers Digest:

Python’s built-in abs(x) function returns the absolute value of the argument 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: 3

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

Test 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:

  1. 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: 3

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

Test 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: 3

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

Test 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: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • 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.
Join the Web Scraping with BeautifulSoup Masterclass now, and master it by tomorrow!



https://www.sickgaming.net/blog/2022/06/...n-integer/
Reply





Users browsing this thread:
1 Guest(s)

𝚂̷𝚒̷𝚌̷𝚔̷𝙶̷𝚊̷𝚖̷𝚒̷𝚗̷𝚐̷ 𝙷̷𝚘̷𝚖̷𝚎̷

Copyright © SickGaming.net 2022