I want to check if there is a specific digit (let’s say 8) in a specific integer (let’s say 83) at a specific place (let’s say second place). In this example, the answer is True. I wrote the following function :
def check_number(integer: int, digit: int, place: int) -> bool: if str(integer)[::-1][place-1] == str(digit) : return True return False
I want to have the more optimized way (in terms of speed) to do it as possible. Is my algorithm good or is there is better ?
A more optimized (though slightly uglier) approach would be to iterate over the integer and use division along with the modulus to check each digit:
import math def check_number(integer: int, digit: int, place: int) -> bool: while place > 1: integer = math.floor(integer / 10) place -= 1 if integer == 0: return False if integer % 10 == digit: return True else: return False print(check_number(12345, 3, 3)) # True print(check_number(12345, 1, 5)) # True print(check_number(12345, 4, 1)) # False
In the above in order to "queue up" the digit to be checked, we iterate in a
while loop and divide the input by 10 however many times is required to put the digit to be examined in
place into the tens position. Then we check that value using the modulus. Should the input not have a digit in that place, we return false, and likewise we return false should the digit exist but not match the input.
Note that in general the above solution is preferable to a string based solution, because the overhead in creating and manipulating a string is fairly high, much higher than doing simple division of the input integer.