I want to check the first two digits of a number in Python. Something like this:
for i in range(1000):
if(first two digits of i == 15):
print("15")
elif(first two digits of i == 16):
print("16")
Is there a command to check the first two digits of a number? I'd like to avoid commands like if(i>149 and i<160):...
To find last digit of a number, we use modulo operator %. When modulo divided by 10 returns its last digit. To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.
The expression for a two digit number is 10a+b. To solve the first special number you create an algebraic equation. You need to add the sum of the two digits to the product of the two digits to get the original number.
2-digit numbers are the numbers that have two digits and they start from the number 10 and end on the number 99.
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)
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With