How can I get the first two digits of a number?
You can convert your number to string and use list slicing like this:
int(str(number)[:2])
Output:
>>> number = 1520
>>> int(str(number)[:2])
15
Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:
num // 10 ** (int(math.log(num, 10)) - 1)
Function:
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
Output:
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456
You will need to add some checks if it's possible that your input number has less digits than you want.