Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the first two digits of a number?

Tags:

python

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):...

like image 270
John28 Avatar asked Dec 21 '16 20:12

John28


People also ask

How do I extract the first digit of a number?

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.

What is the formula used to find a two digit number?

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.

What is the first two digit number?

2-digit numbers are the numbers that have two digits and they start from the number 10 and end on the number 99.


2 Answers

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
like image 116
ettanany Avatar answered Oct 20 '22 14:10

ettanany


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.

like image 31
dom Avatar answered Oct 20 '22 14:10

dom