Beautiful Days at the Movies : HackerRank Solution in Python
Solution in Python 3
def beautifulDays(i, j, k):
beautifulDays = 0 for day in range(i, j+1):
rev = int(str(day)[::-1])
if abs(rev-day)%k==0:
beautifulDays+=1
return beautifulDays
Explanation
Firstly we declare a variable called beautifulDays and initialize it to 0.
beautifulDays = 0
Then, we use a for loop and iterate from i i.e the starting the day number to j i.e the ending day number using a variable called day.
for day in range(i, j+1):
Inside the for loop, We first find the reverse of the number, We do so by converting day which is an integer into a string and then by indexing we reverse the string and convert it back to an integer. We store the reverse of day in a variable called rev.
rev = int(str(day)[::-1])
def beautifulDays(i, j, k):
beautifulDays = 0 for day in range(i, j+1):
rev = int(str(day)[::-1])
Then, we use an if block to check if the subtraction of day and rev is evenly divisible by k.
If the modulus of absolute value of (day-rev) and k is equal to 0 then it is a beautiful day and thus we increment beautifulDays by 1.
if abs(rev-day)%k==0:
beautifulDays+=1
At the end of our program, we return beautifulDays.
return beautifulDays