Given a non-negative integer
num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Input: num = 14
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
I have been away from my daily streak of solving coding question but I am restarting my quest with this February leetcode challenge question. Here we will have to find how many steps a number need to be reduce to 0 and if the number is even we divide it by 2 and if its odd we substract by 1.
Lets move towards the code, a straight forward question where will iterate till the number becomes 0.We will have use a while loop which will run till num=0 and we have declare a counter variable and initialize it to 0.
def numberOfSteps (self, num: int) -> int:
each iteration we will check if the num is even or odd using if-else condition if it’s even we will divide the num by 2 and update the result in num variable and else part we will substract 1 from the num and update the new value of num.At the end of the if-else loop we will increment the count variable by 1 and once the number becomes 0 we will exit the while loop and return the counter value.
“Real courage Courage is not having the strength to go on, it’s going on when you don’t have the strength. “
As the quote says keep moving and keep hustling….(Cheers:-PN)