close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I get the first two digits of a number in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too.

  2. get the first two digits of a number

    previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too.

Method 1

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

Method 2

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read