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

前端 未结 4 1524
-上瘾入骨i
-上瘾入骨i 2020-12-30 19:31

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(\"         


        
4条回答
  •  心在旅途
    2020-12-30 20:33

    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.

提交回复
热议问题