Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find length of digits in an integer?

In Python, how do you find the number of digits in an integer?

like image 349
Strigoides Avatar asked Feb 03 '10 04:02

Strigoides


People also ask

What is the length of integer?

The length of an integer field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8 bytes.

How do you count the number of digits in a number?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

Can you use Len on an integer?

The integer, float, Boolean, and complex types are examples of built-in data types that you can't use with len() . The function raises a TypeError when the argument is an object of a data type that doesn't have a length.

What is the length of integer variable?

A variable length integer is an encoding of 64-bit unsigned integers into between 1 and 9 bytes. The encoding has the following properties: Smaller (and more common) values use fewer bytes and take up less space than larger (and less common) values.


2 Answers

If you want the length of an integer as in the number of digits in the integer, you can always convert it to string like str(133) and find its length like len(str(123)).

like image 58
GeekTantra Avatar answered Sep 22 '22 02:09

GeekTantra


Without conversion to string

import math digits = int(math.log10(n))+1 

To also handle zero and negative numbers

import math if n > 0:     digits = int(math.log10(n))+1 elif n == 0:     digits = 1 else:     digits = int(math.log10(-n))+2 # +1 if you don't count the '-'  

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8) 1000000 loops, best of 3: 746 ns per loop timeit len(str(2**8)) 1000000 loops, best of 3: 1.1 µs per loop  timeit math.log10(2**100) 1000000 loops, best of 3: 775 ns per loop  timeit len(str(2**100)) 100000 loops, best of 3: 3.2 µs per loop  timeit math.log10(2**10000) 1000000 loops, best of 3: 844 ns per loop timeit len(str(2**10000)) 100 loops, best of 3: 10.3 ms per loop 
like image 32
John La Rooy Avatar answered Sep 19 '22 02:09

John La Rooy