Sick Gaming
[Tut] How to Find Number of Digits in an Integer? - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] How to Find Number of Digits in an Integer? (/thread-99621.html)



[Tut] How to Find Number of Digits in an Integer? - xSicKxBot - 06-23-2022

How to Find Number of Digits in an Integer?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;432006&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p class="has-global-color-8-background-color has-background">To find the number of digits in an integer you can use one of the following methods: <br /><strong>(1) Use Iteration <br />(2) Use str()+len() functions <br />(3) Use int(math.log10(x)) +1 <br />(4) Use Recursion</strong> </p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2><strong>Problem Formulation</strong></h2>
<ul>
<li><strong>Given: </strong>An integer value.</li>
<li><strong>Question: </strong>Find the number of digits in the integer/number given.</li>
</ul>
<p><strong>Test Cases:</strong></p>
<pre class="wp-block-preformatted"><strong>Input</strong>:
num = 123
<strong>Output:</strong> 3
=========================================
<strong>Input:</strong>
num = -123
<strong>Output:</strong> 3
=========================================
<strong>Input:</strong> num = 0
<strong>Output:</strong> 1 </pre>
<h2><strong>Method 1: Iterative Approach</strong></h2>
<p><strong>Approach: </strong></p>
<ul>
<li>Use the built-in <code>abs()</code> method to derive the absolute value of the integer. This is done to take care of negative integer values entered by the user.</li>
<li>If the value entered is 0 then return 1 as the output. Otherwise, follow the next steps.</li>
<li>Initialize a counter variable that will be used to count the number of digits in the integer.</li>
<li>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 (<code>num//10</code>) in each iteration. This will make more sense when you visualize the tabular dry run of the code given below.</li>
<li>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.</li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>
<p><strong>Output: </strong></p>
<pre class="wp-block-preformatted"><strong>Test Case 1:</strong>
Enter an Integer: 123
Number of Digits: 3 <strong>Test Case 2:</strong>
Enter an Integer: -123
Number of Digits: 3 <strong>Test Case 3:</strong>
Enter an Integer: 0
Number of Digits: 1</pre>
<p><strong>Explanation through tabular dry run:</strong></p>
<div class="wp-block-image is-style-default">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="489" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-154-1024x489.png" alt="" class="wp-image-433146" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-154-1024x489.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/06/image-154-300x143.png 300w, https://blog.finxter.com/wp-content/uploads/2022/06/image-154-768x367.png 768w, https://blog.finxter.com/wp-content/uploads/2022/06/image-154.png 1035w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f48e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Readers Digest:</strong></p>
<p class="has-base-2-background-color has-background">Python’s&nbsp;<a rel="noreferrer noopener" href="https://blog.finxter.com/python-built-in-functions/" target="_blank">built-in</a>&nbsp;<code><strong>abs(x)</strong></code>&nbsp;function returns the absolute value of the argument&nbsp;<code>x</code>&nbsp;that can be an integer, float, or object implementing the&nbsp;<code>__abs__()</code>&nbsp;function. For a complex number, the function returns its magnitude. The absolute value of any numerical input argument&nbsp;<code>-x</code>&nbsp;or&nbsp;<code>+x</code>&nbsp;is the corresponding positive value&nbsp;<code>+x</code>. Read more <strong><a href="https://blog.finxter.com/python-abs/" target="_blank" rel="noreferrer noopener">here</a></strong>.</p>
<h2><strong>Method 2: Using <a href="https://blog.finxter.com/python-str-function/" target="_blank" rel="noreferrer noopener">str()</a> and </strong><a href="https://blog.finxter.com/python-len/" target="_blank" rel="noreferrer noopener"><strong>len</strong>()</a></h2>
<p><strong>Approach: </strong>Convert the given integer to a string using Python’s <code>str()</code> 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. </p>
<p>To deal with negative numbers, you can use the <code>abs()</code> 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.</p>
<p><strong>Code:</strong> </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = int(input("Enter an Integer: "))
if num &gt;= 0: digit_count = len(str(num))
else: digit_count = len(str(num)) - 1 # to eliminate the - sign
print("Number of Digits: ", digit_count)</pre>
<p><strong>Output:</strong></p>
<pre id="block-f3547fe9-5cec-4745-8f40-ecd8d43b0fa5" class="wp-block-preformatted"><strong>Test Case 1:</strong><br>Enter an Integer: 123<br>Number of Digits: 3<br><br><strong>Test Case 2:</strong><br>Enter an Integer: -123<br>Number of Digits: 3<br><br><strong>Test Case 3:</strong><br>Enter an Integer: 0<br>Number of Digits: 1</pre>
<p><strong>Alternate Formulation: </strong>Instead of using <code>str(num)</code>, you can also use <em>string modulo</em> as shown below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = abs(int(input("Enter an Integer: ")))
digit_count = len('%s'%num)
print("Number of Digits: ", digit_count)</pre>
<h2><strong>Method 3: Using math Module</strong></h2>
<p><strong>Disclaimer:</strong> 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.</p>
<p><strong>Prerequisites: </strong>To use the following approach to solve this question, it is essential to have a firm grip on a couple of functions:</p>
<ol>
<li><strong>math.log10(x)</strong> – Simply put this function returns a float value representing the base 10 logarithm of a given number. </li>
</ol>
<p><strong>Example:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="625" height="128" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-155.png" alt="" class="wp-image-433478" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-155.png 625w, https://blog.finxter.com/wp-content/uploads/2022/06/image-155-300x61.png 300w" sizes="(max-width: 625px) 100vw, 625px" /></figure>
<p>2. <strong>int(x)</strong> – It is a built-in function in Python that converts the passed argument x to an integer value. For example,&nbsp;<code>int('24')</code>&nbsp;converts the passed string value&nbsp;<code>'24'</code>&nbsp;into an integer number and returns&nbsp;<code>24</code> as the output. Note that the&nbsp;<code>int()</code>&nbsp;function on a float argument rounds it down to the closest integer.</p>
<p><strong>Example:</strong></p>
<figure class="wp-block-image size-full is-resized is-style-default"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-156.png" alt="" class="wp-image-433532" width="538" height="302" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-156.png 768w, https://blog.finxter.com/wp-content/uploads/2022/06/image-156-300x169.png 300w" sizes="(max-width: 538px) 100vw, 538px" /></figure>
<p><strong>Approach: </strong></p>
<ul>
<li>Use the <code>math.log(num)</code> 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. </li>
<li>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. </li>
<li>Thus add 1 to the value returned after converting the base 10 logarithm value to an integer to yield the desired output.</li>
<li>To take care of conditions where:
<ul>
<li>Given number = 0 : return 1 as the output.</li>
<li>Given number &lt; 0 : negate the given number to ultimately convert it to its positive magnitude as: <code>int(math.log10(-num))</code>.</li>
</ul>
</li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
num = int(input("Enter an Integer: "))
if num &gt; 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)</pre>
<p><strong>Output:</strong></p>
<pre id="block-f3547fe9-5cec-4745-8f40-ecd8d43b0fa5" class="wp-block-preformatted"><strong>Test Case 1:</strong><br>Enter an Integer: 123<br>Number of Digits: 3<br><br><strong>Test Case 2:</strong><br>Enter an Integer: -123<br>Number of Digits: 3<br><br><strong>Test Case 3:</strong><br>Enter an Integer: 0<br>Number of Digits: 1</pre>
<h2><strong>Method 4: Using Recursion</strong></h2>
<p>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.</p>
<p><strong>Code</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def count_digits(n): if n &lt; 10: return 1 return 1 + count_digits(n / 10) num = int(input("Enter an Integer: "))
num = abs(num)
print(count_digits(num))</pre>
<p><strong>Output:</strong></p>
<pre id="block-f3547fe9-5cec-4745-8f40-ecd8d43b0fa5" class="wp-block-preformatted"><strong>Test Case 1:</strong><br>Enter an Integer: 123<br>Number of Digits: 3<br><br><strong>Test Case 2:</strong><br>Enter an Integer: -123<br>Number of Digits: 3<br><br><strong>Test Case 3:</strong><br>Enter an Integer: 0<br>Number of Digits: 1</pre>
<h2><strong>Exercise</strong></h2>
<p><strong>Question: </strong>Given a string. How will you cont the number of digits, letters, spaces and other characters in the string?</p>
<p><strong>Solution:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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}')</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>No. of Digits = 2
No. of Letters = 13
No. of Spaces = 2
No. of Other Characters = 1</code></pre>
<p><strong>Explanation: </strong>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 <code>sum()</code> 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.</p>
<ul>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-isdigit/" target="_blank">isdigit()</a></strong>: Checks whether all characters in a given are digits, i.e., numbers from 0 to 9 (<code>True</code>&nbsp;or&nbsp;<code>False</code>). </li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-isalpha/" target="_blank">isalpha():</a></strong> Checks whether all charactersof a given string are alphabetic (<code>True</code>&nbsp;or&nbsp;<code>False</code>).</li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-isspace/" target="_blank">isspace():</a></strong> Checks whether all characters are whitespaces (<code>True</code>&nbsp;or&nbsp;<code>False</code>).</li>
<li><a href="https://blog.finxter.com/python-sum/" target="_blank" rel="noreferrer noopener"><strong>sum()</strong>:</a> returns the sum of all items in a given iterable.</li>
</ul>
<h2>Conclusion</h2>
<p>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&nbsp;<strong><a rel="noreferrer noopener" href="https://www.youtube.com/channel/UCRlWL2q80BnI4sA5ISrz9uw" target="_blank">stay tuned</a></strong>&nbsp;and&nbsp;<strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong>&nbsp;for more interesting coding problems.</p>
<p class="has-text-align-center has-base-background-color has-background"><strong>Recommended Read: <a href="https://blog.finxter.com/how-to-count-the-number-of-words-in-a-string-in-python/" target="_blank" rel="noreferrer noopener">Coding Interview Questions</a></strong></p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p class="has-text-align-center"><strong>Recommended:&nbsp;</strong><a href="https://academy.finxter.com/" target="_blank" rel="noreferrer noopener"><strong>Finxter Computer Science Academy</strong></a></p>
<ul>
<li>One of the most sought-after skills on Fiverr and Upwork is&nbsp;<strong>web scraping</strong>. Make no mistake:&nbsp;<em><strong>extracting data programmatically from websites&nbsp;</strong></em>is a critical life skill in today’s world that’s shaped by the web and remote work.</li>
<li>So, do you want to master the art of web scraping using Python’s BeautifulSoup?</li>
<li>If the answer is yes – this course will take you from beginner to expert in Web Scraping.</li>
</ul>
<div class="wp-block-image is-style-default">
<figure class="aligncenter"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/" target="_blank" rel="noreferrer noopener"><img loading="lazy" width="480" height="360" src="https://blog.finxter.com/wp-content/uploads/2021/06/scrape_bs4.png" alt="" class="wp-image-32250" srcset="https://blog.finxter.com/wp-content/uploads/2021/06/scrape_bs4.png 480w, https://blog.finxter.com/wp-content/uploads/2021/06/scrape_bs4-300x225.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></a><figcaption><strong><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/" target="_blank" rel="noreferrer noopener">Join the Web Scraping with BeautifulSoup Masterclass</a></strong>&nbsp;now, and master it by tomorrow!</figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/06/22/how-to-find-number-of-digits-in-an-integer/